使用Reflection创建HttpPostedFile的实例
有没有办法用Reflection创建HttpPostedFile的实例。
我试过了:
var obj = (HttpPostedFile)typeof(HttpPostedFile).GetConstructor( BindingFlags.NonPublic | BindingFlags.Instance, null, Type.EmptyTypes, null).Invoke(null); var obj2 = Activator.CreateInstance(typeof(HttpPostedFile) , BindingFlags.NonPublic | BindingFlags.Instance , null , new object[] { } , System.Globalization.CultureInfo.CurrentCulture);
但他们俩都行不通。
更新:显然内部构造函数如下所示:
internal HttpPostedFile(string filename, string contentType, Stream stream)
我试过这个但没有成功:
Stream s = new MemoryStream(b.blob); //var httpPostedFile = new HttpPostedFile(); Type[] parameters = { typeof(string), typeof(string), typeof(Stream) }; var obj = (HttpPostedFile)typeof(HttpPostedFile).GetConstructor( BindingFlags.NonPublic | BindingFlags.Instance, null, parameters, null) .Invoke(new object[] { "filename", "image/jpeg", s });
我会走另一条路。 只需添加一个抽象级别:创建一个IHttpPostedFile
接口,其中包含您需要的所有成员,并在您的代码和测试中使用它们。 当你有这个接口时,你有两种方法可以:你可以使用duck typing来将IHttpPostedFile
“ IHttpPostedFile
转换”为标准的HttpPostedFile
或者你可以在你自己的类中实现这个接口,它将调用转发给HttpPostedFile
类的聚合实例。
HttpPostedFile类期望HttpInputStream类的实例不是MemeoryStream。 HttpInputStream再次是一个内部类,因此您需要使用reflection创建它。 你真的需要这样做吗?