尴尬的标题我知道,最好在代码中解释。给定一组类:鉴于一个受限制的泛型方法,我可以调用一个非泛型方法来传递泛型参数的实际类型。
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; }
}
有没有编写调用传递泛型类型,而解释传递类型为实际类型而不是基本类型非泛型方法泛型方法的一种方式。也就是说,我想向写的是这样的:因为T被解释为基本型
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));
}
但显然theType。我知道我可以用这样的反思:
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 });
但它只是感觉不雅。有没有更好的办法?
-1这将始终与调用基类的重载的方法,从来没有专门的班级。 – 2011-04-15 12:22:10
你错了我的朋友。如果你通过一只长颈鹿,并且你有长颈鹿和动物的重载,它将使用正确的过载。 – Aliostad 2011-04-15 12:23:28
是的,但是如果你正在处理它们的集合,比如说IEnumerable,那么它将成为动物,无论是长颈鹿还是袋熊。但是,对于具有正确派生类型的单个T,您是正确的。 –
2011-04-15 12:36:28