dimanche 3 octobre 2021

How to get values from derived classes by reflection in C# dynamically?

I have this code with one base class and two derived classes :

public abstract class BaseClass
    {
        public BaseClass(string message)
        {
            //TODO
        }
        public abstract int ErrorCode { get;  }
        public abstract string ErrorName { get; }
    }

    public class Concrete1 : BaseClass
    {
        public Concrete1(int p1, string message) : base(message)
        {
            //TODO
        }

        public override int ErrorCode { get; } = 1022;
        public override string ErrorName { get; } = "NotFound";
    }
    public class Concrete2 : BaseClass
    {
        public Concrete2(int p1, int p2, string message) : base(message)
        {
            //TODO
        }

        public override int ErrorCode { get; } = 1023;
        public override string ErrorName { get; } = "NotSettle";
    }

Now I want to get all derived classes by using reflection and getting their parameter values including ErrorCode and ErroName. this is my code for getting all derived classes that is working:

 public static List<Type> GetAllDerivedTypes(Type type)
    {
        var assemblies = AppDomain.CurrentDomain.GetAssemblies();
        _listTypes = new List<Type>();
        foreach (var item in assemblies)
        {
            _listTypes.AddRange(item
                .GetTypes()
                .Where(t => t != type && type.IsAssignableFrom(t))
                .ToList());
        }

        return _listTypes;
    }

but for getting values my code doesn't work:

   var listOfDerived = GetAllDerivedTypes(typeof(ExceptionBase));
        var src = listOfDerived.First();//for instance

        Type[] emptyArgumentTypes = Type.EmptyTypes;
        var p = ((ObjectType)Activator.CreateInstance(src, true)).GetType().GetConstructor(emptyArgumentTypes);

How can I solve this problem?





Aucun commentaire:

Enregistrer un commentaire