我可以创建一个接受 C# 中两种不同类型的泛型方法吗
我可以创建一个接受两种类型的通用方法吗? attributeType
和 ts_attributeType
不共享任何公共父类,尽管它们具有相同的字段。
这可能吗?或者有什么方法可以实现这一点?
private static void FieldWriter<T>(T row)
where T : attributeType, ts_attributeType
{
Console.Write(((T)row).id + "/" + (((T)row).type ?? "NULL") + "/");
}
我已经看到这个 来自的答案Jon Skeet,但是我不确定它是否也适用于我的问题。
一些进一步的背景: attributeType
和 ts_attributeType
都是使用 xsd.exe 工具创建的;和 是部分类。
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.
Is this possible? Or is there some way I can achieve this?
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.
Some further background:
Both attributeType
and ts_attributeType
have been created using the xsd.exe tool; and are are partial classes.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不,你不能。最简单的替代方法是简单地编写两个重载,每个重载对应一种类型。如果您想避免太多重复,您始终可以提取通用代码:
或者,如果您使用 C# 4,则可以使用动态类型。
(更好的解决方案是给两个类如果可以的话,使用通用接口 - 并同时将它们重命名为遵循 .NET 命名约定:)
编辑:现在我们已经看到您可以使用部分类,您根本不需要它是通用的:
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:
Alternatively, you could use dynamic typing if you're using C# 4.
(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 :)
EDIT: Now that we've seen you can use partial classes, you don't need it to be generic at all:
如果它们是分部类,并且都具有相同的属性,您可以将这些属性提取到接口中并将其用作通用约束。
然后创建一个与您的 2 个类匹配的分部类,并简单地实现接口:
现在您可以通过接口约束泛型:
If they are partial classes, and both have the same properties, you could extract those properties into an interface and use that as your generic constraint.
Then create a partial class matching your 2 classes, and simply implement the interface:
Now you can constrain the generic by the interface:
我当前的解决方案涉及创建一个接口并让分部类实现它。逻辑上有点落后。
My current solution involves creating an interface and letting the partial classes implement it. Slightly backwards in logic.