且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我可以创建一个通用的方法,接受两种不同的类型在C#

更新时间:2022-12-17 15:56:49

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

No, you can't. The simplest alternative is to simply write two overloads, one for each type. You can always extract the common code if you want to avoid repeating yourself too much:

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

或者,您可以 're use C#4。

Alternatively, you could use dynamic typing if you're using C# 4.

(更好的解决方案是给两个类一个通用接口,如果你可以 - 并重命名它们遵循.NET命名约定同一时间:)

(A better solution would be to give the two classes a common interface if you possibly can - and rename them to follow .NET naming conventions at the same time :)

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

Now that we've seen you can use partial classes, you don't need it to be generic at all:

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