简体   繁体   English

具有整数约束的C#泛型方法拒绝从整数转换为泛型类型

[英]C# generic method with integer constraint refuses to cast from integer to the generic type

If I have a generic method that is constrained to be type 'int' then surely I should be able to cast an integer to the generic T type. 如果我有一个被限制为类型'int'的泛型方法,那么我当然应该能够将一个整数转换为泛型T类型。 For example... 例如...

    public T ExampleMethod<T>(int unchanged) where T : int
    {
        return (T)unchanged;
    }

...the compiler complains that Cannot convert type 'int' to 'T' but I have a constraint indicating that the target is as integer. ...编译器抱怨无法将类型'int'转换为'T',但我有一个约束,表明目标是整数。 So surely it should work? 那肯定应该有用吗?

Update: 更新:

The actual scenario is that I want to a helper method that returns an enum value. 实际情况是我想要一个返回枚举值的辅助方法。 So my ideal helper method would be more like this.... 所以我理想的助手方法会更像这样....

public T GetAttributeAsEnum<T>(XmlReader reader, string name) where T : enum
{
    string s = reader.GetAttribute(name);
    int i = int.Parse(s);
    return (T)i;
}

...and use it like this... ......并像这样使用它......

StateEnum x = GetAttributeAsEnum<StateEnum>(xmlReader, "State");
CategoryEnum y = GetAttributeAsEnum<CategoryEnum>(xmlReader, "Category");
OtherEnum z = GetAttributeAsEnum<OtherEnum>(xmlReader, "Other");

...but you cannot constrain by enum. ......但你无法通过枚举来约束。

" Only class or interface could be specified as constraint. " (c) ReSharper 只能将类或接口指定为约束。 ”(c)ReSharper

int (Int32) is just a struct. int(Int32)只是一个结构。 You can constrain that T is a struct . 您可以约束T是结构 but you can't use any struct as constraint. 但你不能使用任何结构作为约束。

the whole list of possible constraints you can find here - http://msdn.microsoft.com/en-us/library/d5x73970.aspx 你可以在这里找到可能的约束的完整列表 - http://msdn.microsoft.com/en-us/library/d5x73970.aspx

UPD UPD

and for Enum constraint see this question - Is there a workaround for generic type constraint of "special class" Enum in C# 3.0? 对于Enum约束,请参阅此问题 - C#3.0中是否存在“特殊类”Enum的泛型类型约束的解决方法?

int (and all other numeric types, and enums) cannot be used as a generic constraint. int (以及所有其他数字类型和枚举)不能用作通用约束。

See 看到

Generic C# Code and the Plus Operator 通用C#代码和Plus运算符

for further details and options. 了解更多详情和选项。

For a discussion with Anders Hejlsberg, the creator of C#, about generics and type constraints see 有关C#的创建者Anders Hejlsberg的讨论,请参阅泛型和类型约束

http://www.artima.com/intv/generics.html http://www.artima.com/intv/generics.html

One can place a type constraint of struct like this: 可以像这样放置struct的类型约束:

public class Generic<T> where T : struct { }

Generic<int> gen = new Generic<int>();

Are you sure its compiling? 你确定它的编译?

Here, it gives following error: 在这里,它给出以下错误:

error CS0701: 'int' is not a valid constraint. 错误CS0701:'int'不是有效约束。 A type used as a constraint must be an interface, a non-sealed class or a type parameter. 用作约束的类型必须是接口,非密封类或类型参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM