如何处理重载方法签名冲突?
我感觉这个问题很棘手,但我还是要问...:)
我有一个方法:
private MembershipUser GetUserFromReader(SqlDataReader reader)
并且我想用不同的返回类型重载这个方法:
private User GetUserFromReader(SqlDataReader reader)
但是编译器抱怨这两个方法有相同的签名。
那么,最好的方法是什么?我不想添加不必要的 参数只是为了更改方法签名。
我曾考虑过做类似的事情:
private User GetUserFromReader(T reader)
但还没有真正全面探索这一点。看来我需要做一个 我使用阅读器对象的方式发生了一些变化。
有什么想法吗?当您有两个超载时,最佳实践是什么 相同签名的方法?
谢谢你帮忙...
I have a feeling this question is a can of worms but I am going to ask anyway... :)
I have a method:
private MembershipUser GetUserFromReader(SqlDataReader reader)
And I want overload this method with a different return type:
private User GetUserFromReader(SqlDataReader reader)
But the compiler complains that the two methods have the same signature.
So, what is the best way to do this? I would prefer to not add an unnecessary
parameter just to change the method signature.
I have played with the idea of doing something like:
private User GetUserFromReader(T reader)
But haven't really explored this in full yet. It seems like I'll need to make a
bunch of changes with how I use my reader object.
Any ideas? What is the best practice when you have two overloaded
methods of the same signature?
Thanks for helping out...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
为什么要超载呢?为什么不直接让方法说出它的作用,如下所示:
Why overload it? Why not just let the method say what it does, like so:
如果您确实想区分返回类型,但使用相同的方法签名,则可以使用泛型:
但仅重命名方法要简单得多,如 Luhmann 的答案所示。
If you really want to differentiate the return type, but use the same method signature, you could use generics:
But it's much simpler to just rename the methods, as in Luhmann's answer.
您唯一真正的选择是:
我讨厌陈词滥调,但没有办法绕过仅通过返回类型区分方法的限制。
如果在父类中声明了其中一个重载,则可以使用 new 关键字对调用者“隐藏”更高层的方法,但 new (在成员声明上)通常被认为是邪恶的。
Your only real options are:
I hate to be trite, but there isn't a way around the restriction on differentiating methods solely by return type.
If one of the overloads is declared in a parent class then you can use the
new
keyword to "hide" the higher method from callers, butnew
(on a member declaration) is usually considered evil.您无法更改重载的返回类型。编译器如何判断您要使用哪一个?
您应该做的是返回您可能想要返回的所有内容的公共超类,然后仅返回适用的内容。
要么这样,要么以不同的方式命名这些方法,因为它们显然做不同的事情。
You can't change the return type on an overload. How is the compiler supposed to tell which one you want to use?
What you should do is return a common superclass of everything you might want to return, and then just return whatever is applicable.
Either that, or name the methods differently, since they clearly do different things.
简单的答案是,就 C# 而言,您不能。 MSIL 允许按返回类型重载(我认为),但 C# 不允许。
唯一真正的选择(即,排除添加“虚拟”参数)是调用一个方法 GetMembershipUserFromReader 和另一个 GetUserFromReader
The simple answer is that, as far as C# is concerned, you can't. Overloading by return type is permitted (I think) by MSIL, but not by C#.
The only real choice (i.e, excluding adding a "dummy" parameter), is to call one method GetMembershipUserFromReader and the other GetUserFromReader