using the where clause + new constraint with args?
I have a piece of code that looks like this:
public static T CreateSomething<T>(SomeType a) where T : SomeMicrosoftBaseClass, new()
{
var newElement = new T { SomeProperty = a};
DoStuff();
return newElement;
}
and now I need to change the code so I could pass to the constructor of SomeMicrosoftBaseClass a boolean argument - which I can only set on construction.
since the "new()" constraint requires a public parameter-less constructor, and since I couldn't use an interface or modify SomeMicrosoftBaseClass, I'm using reflection like so:
var newElement = (T) (typeof (T).GetConstructor(new Type[] { typeof(SomeType) }).Invoke(new object[] { a }));
can anybody suggest a more el开发者_StackOverflow中文版egant way to do this?
Maybe you can use Activator.CreateInstance:
var newElement = (T)Activator.CreateInstance(typeof(T),a);
精彩评论