Is it possible to create a CreateInstance object with a protected constructor?

I greet my colleagues, the situation in question is as follows:

public abstract class BaseClass
{
    protected BaseClass()
    {
        // some logic here
    }

    protected BaseClass(Object parameter) : this()
    {
        // some more logic
    }
}

public class Descendant : BaseClass
{
   // no constructors
}

I am trying to call Activator.CreateInstance in the Descendant class, but no constructor was found .

Do I need to explicitly define it in the Descentant class?

The links I used are as follows: BindingFlags.Instance | BindingFlags.NonPublic

Note 1 . I find the AppDomain.CreateInstanceAndUnwrap () application in reality if it should have any effect.

 domain.CreateInstanceAndUnwrap(path, typeName, false, BindingFlags.Instance |
     BindingFlags.NonPublic, null, new[] { parameter }, null, null);

Note 2 . If I explicitly define a protected constructor in the Descendant class, then it works, but I would like to avoid this if possible.

+3
source share
2

Activator.CreateInstance, .

, Descendant , . :

Activator.CreateInstance(typeof(Descendant))

a >

, , , . . , . ( , ) .

Descendant, , . , , :

// Define other methods and classes here
public abstract class BaseClass
{
    protected BaseClass()
    {
        // some logic here
    }

    protected Object Parameter {get; private set;}    

    public virtual void Initialize(Object parameter)
    {
        Parameter = _parameter;
        // some more logic
    }
}
+4

, , , . - ( ), "" , . - ( : ):

public abstract class BaseBuildable : MarshalByRefObject {
   public String Foo { get; internal set; }
}

public class DerivedBuildable : BaseBuildable { }

public class BuildableBuilder : MarshalByRefObject {
   private String _foo;
   public BuildableBuilder WithFoo(String foo) { _foo = foo; return this; }
   public TBuildable Build<TBuildable>() where TBuildable : BaseBuildable, new() {
       return new TBuildable { Foo = _foo; }
   }
}

// Used so:
var builder = domain.CreateInstanceAndUnwrap(.. // yadda yadda, you want a BuildableBuilder
var buildable = builder.WithFoo("Foo, yo").Build();
+1

All Articles