C#泛型方法的返回值 [英] C# Generic method return values
问题描述
我只是在学习泛型和有关于方法的返回值的问题。
I'm just learning about generics and have a question regarding method return values.
我说,我要达到规定的通用部分在这个意义上泛型方法方法签名是唯一的返回值。该方法将始终以一根弦,因为它是参数,但可以返回一张双人床或int。这可能吗?
Say, I want a generic method in the sense that the required generic part of the method signature is only the return value. The method will always take one string as it's parameter but could return either a double or an int. Is this possible?
切实我想带一个字符串,分析其中所包含的数字(可以是双重或int),然后返回值。
Effectively I want to take a string, parse the number contained within (which could be a double or an int) and then return that value.
感谢。
推荐答案
您不能返回一个双
或 INT
从没有它也返回任何其他类型的泛型方法。
You cannot return either a double
or an int
from a generic method without it also returning any other type.
我可能,例如,有一个富
类和你一般的解析方法,没有任何限制,将允许进行此调用:
I might, for example, have a Foo
class and your generic parse method, without any constraint, will allow this call to be made:
Foo result = Parse<Foo>("111");
,您可以用数字做的最好的是由只允许结构
(价值型)中使用
T Parse<T>(string value) where T : struct;
但是,这将允许所有号码类型,以及任何其他值类型。
But this will allow all number types, plus any other value-type.
您可以通过接口类型限制,但没有对双击$ C $的
INumeric
接口C>或 INT
让你有种被卡住。
You can constrain by interface type, but there isn't an INumeric
interface on double
or int
so you're kind of stuck.
这是你能做的唯一的事情就是抛出如果错误的类型在通过异常 - 这通常是不很满意的
The only thing that you can do is throw an exception if the wrong type is passed in - which generally isn't very satisfying.
您最好的方法,在这种情况下,是放弃泛型和使用单独命名的方法。
Your best approach, in this case, is to abandon generics and use separately named methods.
double ParseDouble(string value);
int ParseInteger(string value);
但是,当然,这不会帮助你学习泛型。对不起。
But, of course, this won't help you learn generics. Sorry.
这篇关于C#泛型方法的返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!