即时设置通用名称

| 我对泛型有一个疑问,我认为这可能是不可能的,但我想把它扔在那里,希望找到某种解决方案。 我有一个使用泛型的对象,我想即时设置泛型。我的问题是,或者反射之所以无法解决我的问题,是因为该对象需要作为out参数发送到方法中。有什么建议么?代码如下
GetConfigurationSettingMessageResponse<DYNAMICALLYSETTHIS> ch;
if (MessagingClient.SendSingleMessage(request, out ch))
{
    if (ch.ConfigurationData != null)
    {
        data = ch.ConfigurationData;
    }
}
    
已邀请:
如何创建通用的便捷方法,然后使用反射进行调用。
void HelperMethod<TType>(){
    GetConfigurationSettingMessageResponse<TType> ch;
    if (MessagingClient.SendSingleMessage(request, out ch))
    {
        ... //Do your stuff.
    }

}
    
除直接答案外,还可以提供其他解决方法,但是您是否必须编写强类型代码?也许您将其保留为
GetConfigurationSettingMessageResponse<object>
,并在稍后阶段进行测试以了解其含义:
void SendSingleMessage(int request, out GetConfigurationSettingMessageResponse<object> obj)
{
    if (obj.InnerObject is Class1)
    {...}
    else if...
..
}
...
   class GetConfigurationSettingMessageResponse<T>
    {
        public T _innerObject { get; set; }
    }
    
编辑:本质上,您需要传递对在编译时不知道的类型的引用。在这种情况下,我们需要克服通过反射进行的编译时检查。
using System.Reflection;

public class ResponseWrapper {

  public static ConfigurationData GetConfiguration( Request request, Type dtype  )
  {
    // build the type at runtime
    Type chtype = typeof(GetConfigurationSettingMessgeResponse<>);
    Type gchtype = chtype.MakeGenericType( new Type[] { dtype } );

    // create an instance. Note, you\'ll have to know about your 
    // constructor args in advance. If the consturctor has no 
    // args, use Activator.CreateIntsance.

    // new GetConfigurationSettingMessageResponse<gchtype>
    object ch = Activator.CreateInstance(gchtype); 


    // now invoke SendSingleMessage ( assuming MessagingClient is a 
    // static class - hence first argument is null. 
    // now pass in a reference to our ch object.
    MethodInfo sendsingle = typeof(MessagingClient).GetMethod(\"SendSingleMessage\");        
    sendsingle.Invoke( null, new object[] { request, ref ch } );

    // we\'ve successfulled made the call.  Now return ConfigurtationData

    // find the property using our generic type
    PropertyInfo chcd = gchtype.GetProperty(\"ConfigurationData\");
    // call the getter.
    object data = chcd.GetValue( ch, null );

    // cast and return data
    return data as ConfigurationData;


  }

}
完成此操作后,您可以创建一个辅助方法来处理ch对象而不是GetProperty部分。     

要回复问题请先登录注册