문제

I have a base program that impliments an abstract class.

public abstract class AbstractClass
{
    public AbstractClass (MyObject object1, MyOtherObject object2)
    {
        Console.WriteLine("This is the abstract class");
    }

    public abstract bool Function1();
    <other abstract functions>
}

Right now I build and compile seperate versions of my application when I want to do different things and have implemented different abstract classes for these things. I find this to be tedious.

I'd like to be able to take this line of code

new MySuperSpecialClassOfThings(param1, (MyObject obj1, MyOtherObject obj2) => 
{
    return new NotAnAbstractClass(obj1, obj2);
}, true);

And change it to something like:

new MySuperSpecialClassOfThings(param1, (MyObject obj1, MyOtherObject obj2) => 
{
    return new System.Activator.CreateInstance(Type.GetType(config.NonAbstractClassName), new object[] { obj1, obj2 });
}, true);

Where config.NonAbstractClassName is a string provided in a configuration file. This fails, though, with the error: 'System.Activator.CreateInstance(System.ActivationContext, string[])' is a 'method' but is used like a 'type'

obj1 and obj2 are not strings. They are classes.

How can I do this?

도움이 되었습니까?

해결책

Get rid of the new before CreateInstance:

new MySuperSpecialClassOfThings(param1, (MyObject obj1, MyOtherObject obj2) => 
{
    return (AbstractClass)System.Activator.CreateInstance(Type.GetType(config.NonAbstractClassName), new object[] { obj1, obj2 });
}, true);

다른 팁

Just remove "new" keyword..CreateInstance return new instance of object based on type on parameter..so basically you don't need "new" keyword

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top