我可以创建一个在C#中接受两种不同类型的generics方法吗

我可以创建一个接受两种类型的通用方法。 尽管attributeTypets_attributeType具有相同的字段,但它们不共享任何公共父类。

这可能吗? 或者有什么办法可以实现这个目标吗?

 private static void FieldWriter(T row) where T : attributeType, ts_attributeType { Console.Write(((T)row).id + "/" + (((T)row).type ?? "NULL") + "/"); } 

我从Jon Skeet看到了这个答案 ,但我不确定它是否也适用于我的问题。

一些进一步的背景:使用xsd.exe工具创建了attributeTypets_attributeType ; 并且是部分类。

不,你不能。 最简单的选择是简单地写两个重载,每个类型一个。 如果您想避免过多地重复自己,可以随时提取公共代码:

 private static void FieldWriter(attributeType row) { FieldWriterImpl(row.id, row.type); } private static void FieldWriter(ts_attributeType row) { FieldWriterImpl(row.id, row.type); } // Adjust parameter types appropriately private static void FieldWriterImpl(int id, string type) { Console.Write(id + "/" + (type ?? "NULL") + "/"); } 

或者,如果您使用的是C#4,则可以使用动态类型。

(更好的解决方案是在可能的情况下为这两个类提供一个通用接口 – 并将它们重命名为同时遵循.NET命名约定:)

编辑:现在我们已经看到你可以使用部分类,你根本不需要它是通用的:

 private static void FieldWriter(IAttributeRow row) { Console.Write(row.id + "/" + (row.type ?? "NULL") + "/"); } 

如果它们是部分类,并且都具有相同的属性,则可以将这些属性提取到接口中并将其用作通用约束。

 public interface IAttributeType { int id{get;} string type{get;set;} } 

然后创建一个与您的2个类匹配的分部类,并简单地实现该接口:

 public partial class AttributeType : IAttributeType { // no need to do anything here, as long as AttributeType has id and type } public partial class ts_AttributeType : IAttributeType { // no need to do anything here, as long as ts_AttributeType has idand type } 

现在您可以通过界面约束generics:

 private static void FieldWriter(T row) where T : IAttributeType { Console.Write(row.id + "/" + (row.type ?? "NULL") + "/"); } 

我目前的解决方案涉及创建一个接口并让部分类实现它。 逻辑略微倒退。

 namespace Test { public partial class attributeType: IAttributeRow {} public partial class ts_attributeType : IAttributeRow {} public interface ICommonFields { string id { get; set; } string type { get; set; } } } private static void FieldInfo(T row) where T : IAttributeRow { Console.Write(((T)row).id + "/" + (((T)row).type ?? "NULL") + "/"); }