接受两种不同的类型在C#

接受两种不同的类型在C#

本文介绍了我可以创建一个通用的方法,接受两种不同的类型在C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Can I create a generic method that accept two types. The attributeType and ts_attributeType do not share any common parent class although they do have the same fields.

这是可能吗?

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

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

我看过这个,但我不确定是否也适用对我的问题。

I have seen this answer from Jon Skeet, however I am not certain if it also applies to my question.

其他背景:
attributeType ts_attributeType 已使用xsd.exe工具创建;并且是部分类。

Some further background:Both attributeType and ts_attributeType have been created using the xsd.exe tool; and are are partial classes.

推荐答案

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

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

这篇关于我可以创建一个通用的方法,接受两种不同的类型在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 05:16