开发者

using the where clause + new constraint with args?

开发者 https://www.devze.com 2022-12-13 09:46 出处:网络
I have a piece of code that looks like this: public static T CreateSomething<T>(SomeType a) where T : SomeMicrosoftBaseClass, new()

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

精彩评论

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