是否有使用扩展方法实例化和初始化对象的简写?
我的目标是抽象并封装实例化和初始化适合单元测试的MyType实例所需的代码。
示例:
//...
//convoluted client code - I'd like to avoid the null instance creation
MyType t = null;
t = t.GetTestInstance();
//...
//extension method
public static class MyTypeExtensions
{
public static MyType GetTestInstance(this MyType t)
{
var ctorInjectedDependency = blah;
return new MyType(ctorInjectedDependency);
}
}
答案 0 :(得分:1)
也许这样的事情会满足你的需求:
public class MyType
{
public MyType(string s)
{
Property = s;
}
public string Property { get; set; }
}
public static class MyTypeExtensions
{
public static object GetTestInstance(this Type t)
{
var ctorInjectedDependency = "blah";
var ctorInfo = t.GetConstructor(new[]{typeof(string)});
return ctorInfo.Invoke(new object[] {ctorInjectedDependency});
}
public static T GetTestInstance<T>(this Type t)
{
var ctorInjectedDependency = "blah";
var ctorInfo = t.GetConstructor(new[] { typeof(string) });
return (T)ctorInfo.Invoke(new object[] { ctorInjectedDependency });
}
}
用法:
var my = typeof(MyType).GetTestInstance(); // maybe just object is enough
var my2 = typeof(MyType).GetTestInstance<MyType>();
Console.WriteLine((my as MyType).Property);
Console.WriteLine(my2.Property);