How to choose the "right" constructor for Activator.CreateInstance

When using the .NET method, Activator.CreateInstanceI pass the type and parameters for this constructor. Some types received several such constructors:

public foo(Status status, TServiceReference listService, 
    Int32 listID, Int16 clientID)
{
    Status = status;
    ListService = listService;
    ListID = listID;
    ClientID = clientID;
}

public foo(Status status, String listServiceRegexCompare, 
    Int32 listID, Int16 clientID)
{
    Status = status;
    ListServiceRegexCompare = listServiceRegexCompare;
    ListID = listID;
    ClientID = clientID;
}

If at run time the second parameter null, I always need a constructor to select. Is there any way to achieve this? (Note that I call Activator.CreateInstancefor several different types, and for another type, the constructor may expect a different calculation of the parameters of different course types). But again, I always want a constructor that does NOT expect the string to be called, and pass a null object for this parameter.

Thank.

Edit:

I call a method like this

public void ActivateEvent(Object instance, EventInfo eventInfo, 
    ILoggingSupport logger, params Object[] parameter)
    {
        Delegate handler = 
            Delegate.CreateDelegate(
                eventInfo.EventHandlerType, this, 
                GetType().GetMethod("Handler"));

        _instance = instance;
        _eventInfo = eventInfo;
        _handler = handler;
        _logger = logger;

        eventInfo.AddEventHandler(instance, handler);

        Type eventArgsType = 
            eventInfo.EventHandlerType.GetGenericArguments()[0];

        _referenceArgs = 
            Activator.CreateInstance(eventArgsType, parameter) as IComparable;
    }
+4
source share
1

, , , , . , , , . ( ), . , .

, CreateInstance, . . , . , ,

public void ActivateEvent<T1,T2>(Object instance, EventInfo eventInfo, 
ILoggingSupport logger, T1 p1, T2 p2)
{
  ...
  var parameterTypes = new []{typeof(T1), typeof(T2)};
  var arguments = new object[]{p1,p2};
  var ctor = eventArgsType.GetConstructor(parameterTypes);
  _referenceArgs = ctor.Invoke(arguments) as IComparable;
}

Activator.CreateInstance, , .

0

Source: https://habr.com/ru/post/1548734/


All Articles