开发者

Shorthand for instantiation and initialization using an extension method

Is there any shorthand for using an extension method to instantiate and initialise an object?

My aim is to abstract-away and encapsulate the code required to instantiate and initialise an instance of MyType suitable for unit testing.

Example:

//...
//convoluted client code - I'd like to avoid the null instance creation
MyType t = null;
t = t.GetTestInstanc开发者_StackOverflow中文版e();
//...

//extension method
public static class MyTypeExtensions
{
  public static MyType GetTestInstance(this MyType t)
  {
    var ctorInjectedDependency = blah;

    return new MyType(ctorInjectedDependency);
  }
}


Maybe something like this will suit your needs:

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 });
  }
}

Usage:

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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜