给定一个受约束的泛型方法,我可以调用传递泛型参数的实际类型的非泛型方法吗
|
我知道标题很尴尬,最好用代码说明。给定一组类:
public abstract class MyBaseType
{
public string Message { get; set; }
}
public class MySuperType : MyBaseType
{
public string AdditionalInfo { get; set; }
}
public class MyOtherSuperType : MyBaseType
{
public DateTime Started { get; set; }
public DateTime Finished { get; set; }
}
有没有一种写通用方法的方法,该方法调用传递通用类型的非通用方法,同时将传递的类型解释为实际类型而不是基本类型。也就是说,我想写这样的东西:
public void OutputFormattedTypeInfo<T>(T theType) where T : MyBaseType
{
OutputFormattedTypeInfo(theType as T);
}
public void OutputFormattedTypeInfo(MySuperType theType)
{
System.Console.WriteLine(String.Format(\"{0} and {1}\", theType.Message, theType.AdditionalInfo));
}
public void OutputFormattedTypeInfo(MyOtherSuperType theType)
{
System.Console.WriteLine(String.Format(\"{0} - Start: {1}, End: {2}\", theType.Message, theType.Started, theType.Finished));
}
但是很明显,将Type作为T解释为基本类型。我知道我可以这样使用反射:
Type type = typeof(MyBaseTypeDisplayFormatter);
MethodInfo method = type.GetMethod(
\"FormatSpecific\",
BindingFlags.Instance | BindingFlags.NonPublic,
null,
new[] { update.GetType() },
null);
return (MyBaseTypeDataItem)method.Invoke(this, new object[] { update });
但是感觉很不雅有没有更好的办法?
没有找到相关结果
已邀请:
2 个回复
貉骂
其中GetTypeSpecific方法使用反射来创建委托
拈吉勉犬姆
,因此您最好也不要使用泛型方法,而只需使用重载(这里不需要泛型):