2011-04-14 66 views
2

尴尬的标题我知道,最好在代码中解释。给定一组类:鉴于一个受限制的泛型方法,我可以调用一个非泛型方法来传递泛型参数的实际类型。

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

正如Aliostad说,你试图做的不再是通用的,只是使用重载会更好。看起来你正在尝试在C++中做类似于模板特化的事情,其中​​根据泛型来调用不同的方法。

下面是一个例子,我使用反射实现了一种通用专业化,如果重载方法不适合您,也许可以应用类似的模式。如果你可以缓存反射结果并且只调用一次GetMethod,那么结果不会太慢。里面的一类通用的T有一个调用方法:

if (_serializeDataToStream == null) 
    _serializeDataToStream = (Action<BinaryWriter, int, T[]>)GetTypeSpecificSerializationMethod(); 

_serializeDataToStream(writer, _size, _data); 

凡GetTypeSpecific方法使用反射来创建一个委托

/// <summary> 
/// Returns a delegate that points at the static type specific serialization method 
/// </summary> 
/// <returns></returns> 
private Delegate GetTypeSpecificDeserializationMethod() 
{ 
    if (typeof(T) == typeof(double)) 
    { 
     MethodInfo method = this.GetType().GetMethod("DeserializeDouble", BindingFlags.Static | BindingFlags.NonPublic); 
     return Delegate.CreateDelegate(typeof(Action<BinaryReader, int, T[]>), method); 
    } 
    else if (typeof(T) == typeof(ushort)) 
    { 
     MethodInfo method = this.GetType().GetMethod("DeserializeUshort", BindingFlags.Static | BindingFlags.NonPublic); 
     return Delegate.CreateDelegate(typeof(Action<BinaryReader, int, T[]>), method); 
    } 
    else if (typeof(T) == typeof(DateTime)) 
    { 
     MethodInfo method = this.GetType().GetMethod("DeserializeDateTime", BindingFlags.Static | BindingFlags.NonPublic); 
     return Delegate.CreateDelegate(typeof(Action<BinaryReader, int, T[]>), method); 
    } 
    else if (typeof(T) == typeof(bool)) 
    { 
     MethodInfo method = this.GetType().GetMethod("DeserializeBool", BindingFlags.Static | BindingFlags.NonPublic); 
     return Delegate.CreateDelegate(typeof(Action<BinaryReader, int, T[]>), method); 
    } 

    throw new NotImplementedException("No deserialization method has been setup for type " + typeof(T).FullName); 
} 

/// <summary> 
/// Serialize double[] to BinaryWriter 
/// </summary> 
/// <param name="writer"></param> 
/// <param name="size"></param> 
/// <param name="data"></param> 
private static void SerializeDouble(BinaryWriter writer, int size, double[] data) 
{ 
    for (int i = 0; i < size; i++) 
    { 
     writer.Write(data[i]); 
    } 
} 
1

这里的问题是你没有真正表达一般性。你必须实现OutputFormattedTypeInfo对于每一个基本类型,所以你不如忘了泛型方法和简单地使用重载你并不需要仿制药在这里):

public void OutputFormattedTypeInfo(BaseType theType) 
{ 
    // ... 
} 

public void OutputFormattedTypeInfo(MySuperType theType) 
{ 
    // ... 
} 

public void OutputFormattedTypeInfo(MyOtherSuperType theType) 
{ 
    // ... 
} 
+0

-1这将始终与调用基类的重载的方法,从来没有专门的班级。 – 2011-04-15 12:22:10

+0

你错了我的朋友。如果你通过一只长颈鹿,并且你有长颈鹿和动物的重载,它将使用正确的过载。 – Aliostad 2011-04-15 12:23:28

+0

是的,但是如果你正在处理它们的集合,比如说IEnumerable ,那么它将成为动物,无论是长颈鹿还是袋熊。但是,对于具有正确派生类型的单个T,您是正确的。 – 2011-04-15 12:36:28

相关问题