編輯:從本質上講,你需要在引用傳遞的類型你無法在編譯時知道。在這種情況下,我們需要用反射來挫敗編譯時間檢查。
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;
}
}
一旦你做到了這一點,你可以創建一個輔助方法,讓你maniupulate的通道對象,而不是使用getProperty部分。
什麼是實際問題? – 2011-04-20 20:19:57
是您的'DYNAMICALLYSETTHIS'類型的'ConfigurationData'屬性? – Stormenet 2011-04-20 20:20:23
@Stormenet沒有這是什麼動態的設置 – Lizzard 2011-04-25 15:32:04