gpt4 book ai didi

c# - 将类型限制为特定类型

转载 作者:行者123 更新时间:2023-11-30 13:42:18 27 4
gpt4 key购买 nike

是否可以将泛型方法限制在特定类型上?

我想写这样的东西:

public T GetValue<T>(string _attributeValue) where T : float, string
{
return default(T); // do some other stuff in reality
}

我主要只是试图避免在方法中使用巨大的 switch 语句,或者在指定无效类型时不得不抛出异常。

编辑:确认。我知道 string 不是值类型。我之前开始使用两种数字类型。对不起。

最佳答案

您不能使用泛型约束来表达您感兴趣的限制。泛型并不意味着表达基于不相交类型的变化 - 它们旨在表达统一在类型的层次结构(或实现某些接口(interface)的类型)。

但是,您还有一些其他选择。您选择哪一个取决于您尝试做的事情的确切性质。

使用不同命名的方法来表达每个操作。当每个方法真正做不同的事情时,我倾向于使用这种方法。您可能会争辩说,从方法返回不同类型的值本质上是一种不同的操作,并且值得拥有自己独特的名称。

float GetFloat(string attrName) { }
string GetString(string attrName) { }

提供“默认值”以允许推断类型。在许多您通过名称请求值的设计中,提供默认值很有用。这可以让您使用重载来区分要调用的方法(基于默认值的类型)。不幸的是,这种方法非常脆弱 - 并且在将文字值传递给接受数字基元(int 与 uint 与 long)的重载时很容易崩溃。

float GetValue(string attrName, float defaultValue) { ... }
string GetValue(string attrName, string defaultValue) { ... }

使用泛型方法,但如果类型不是您支持的类型之一,则抛出运行时异常。我个人认为这种丑陋且违反泛型精神 - 泛型应该通过层次结构或实现某些接口(interface)的一组类型统一功能。但是,在某些情况下这样做是有意义的(如果让我们这样说,一种特定的类型不被支持)。这种方法的另一个问题是泛型方法的签名不能从任何参数中推断出来,所以你必须在调用它时指定所需的类型......在这一点上它并没有好多少(从语法的角度来看)而不是使用不同的方法名称。

T GetValue<T>( string attrName )
{
if( typeof(T) != typeof(string) ||
typeof(T) != typeof(float) )
throw new NotSupportedException();
return default(T);
}

// call it by specifying the type expected...
float f = GetValue<float>(attrName);
string s = GetValue<string>(attrName);

使用输出参数而不是返回值。这种方法效果很好,但它失去了能够调用方法并作用于返回值的简洁语法,因为您首先必须声明要填充的变量。

void GetValue( string attrName, out float value )
void GetValue( string attrName, out string value )

// example of usage:
float f;
GetValue( attrName, out f );
string s;
GetValue( attrName, out s );

关于c# - 将类型限制为特定类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3406899/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com