【问题标题】:Can I create a generic method that accepts two different types in C#我可以在 C# 中创建一个接受两种不同类型的泛型方法吗
【发布时间】:2011-10-20 16:57:34
【问题描述】:

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

这可能吗?或者有什么方法可以实现吗?

private static void FieldWriter<T>(T row)
        where T : attributeType, ts_attributeType

    {
        Console.Write(((T)row).id + "/" + (((T)row).type ?? "NULL") + "/");
    }

我看过这个answer from Jon Skeet,但我不确定它是否也适用于我的问题。

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

【问题讨论】:

  • 你能让它们都实现一个共享接口吗?

标签: c# c#-4.0


【解决方案1】:

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

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") + "/");
}

【讨论】:

  • 谢谢乔恩,那么我目前的解决方案是正确的好方法吗?
  • @Ahmad:是的,使用部分类来实现通用接口是一个很好的解决方案,我在其他地方也使用过。不过,我不会称它为 ICommonFields,因为它没有指定 fields :) 它也不需要是通用的 - 将编辑我的答案。
  • 我在原始解决方案中错过了这一点。没有必要有一个通用的约束。谢谢
【解决方案2】:

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

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
}

现在你可以通过接口来约束泛型:

private static void FieldWriter<T>(T row)
    where T : IAttributeType

{
    Console.Write(row.id + "/" + (row.type ?? "NULL") + "/");
}

【讨论】:

  • 这在处理 linq2sql 生成的类时特别有用,这些类都返回相同的表数据,而没有实用的方法为它们提供公共基类。
【解决方案3】:

我当前的解决方案包括创建一个接口并让部分类实现它。逻辑上有点倒退。

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>(T row)
        where T : IAttributeRow 

    {
        Console.Write(((T)row).id + "/" + (((T)row).type ?? "NULL") + "/");
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多