How to call protected constructor in c#?

后端 未结 8 1854
不知归路
不知归路 2021-02-19 00:51

How to call protected constructor?

public class Foo{
  public Foo(a lot of arguments){}
  protected Foo(){}
}
var foo=???

This obviously fails

8条回答
  •  你的背包
    2021-02-19 01:05

    If you want to avoid repeated reflection cost, you can use expressions. Here is an example of calling a private constructor with a string value.

        private static Func CreateInstanceFunc()
        {
            var flags = BindingFlags.NonPublic | BindingFlags.Instance;
            var ctor = typeof(T).GetConstructors(flags).Single(
                ctors =>
                {
                    var parameters = ctors.GetParameters();
                    return parameters.Length == 1 && parameters[0].ParameterType == typeof(string);
                });
            var value = Expression.Parameter(typeof(string), "value");
            var body = Expression.New(ctor, value);
            var lambda = Expression.Lambda>(body, value);
    
            return lambda.Compile();
        }
    

    Save the cost of compiling the function multiple times by storing it in a static field.

    private static readonly Lazy> CreateInstance = new Lazy>(CreateInstanceFunc);
    

    Now you can create the object with

    CreateInstance.Value("Hello")
    

提交回复
热议问题