如何允许方法接受字符串或整数?
使用 C# 4.0,有没有办法允许方法(不创建重载)接受字符串或 int,然后允许我检测传入的类型?
Using C# 4.0, is there a way to allow a method (without creating an overload) to accept a string or an int and then allow me to detect what type was passed in?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
由于您使用的是 C# 4.0,因此您可以编写通用方法。例如:
但是你应该非常认真地考虑这是否是一个好主意。上面的例子有点代码味道。事实上,泛型的全部意义就是泛型。如果您必须根据传入对象的类型对代码进行特殊处理,则表明您应该使用重载。这样,每个方法重载都会处理其独特的情况。我无法想象这样做有什么缺点。
Since you're using C# 4.0, you can write a generic method. For example:
But you should very seriously consider whether or not this is a good idea. The above example is a bit of a code smell. In fact, the whole point of generics is to be generic. If you have to special-case your code depending on the type of the object passed in, that's a sign you should be using overloading instead. That way, each method overload handles its unique case. I can't imagine any disadvantage to doing so.
当然可以!一个例子是
Sure you can! An example of this is
您可以将 string 和 int 包装在带有标记接口的包装器中,并将它们传递给方法。
像这样的东西
You can wrap string and int in some wrapper with marker interface and pass them to a method.
Something like this
如果您想远离反射或检查类型之类的东西,我认为方法重载将是一个简单的解决方案。
I would think a method overload would be a straightforward solution, if you want to stay away from stuff like reflection or checking types.