开发者

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜