带整数约束的C#泛型方法拒绝从整型转换为泛型类型 [英] C# generic method with integer constraint refuses to cast from integer to the generic type

查看:806
本文介绍了带整数约束的C#泛型方法拒绝从整型转换为泛型类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个被限制为'int'类型的泛型方法,那么当然我应该能够将一个整型转换为泛型T型。例如...

p $ p $ public T ExampleMethod< T>(int不变)其中T:int
{
回报(T)不变;
}

...编译器抱怨无法将类型'int'到'T'但我有一个约束表明目标是整数。所以肯定它应该工作?



更新:

实际情况是我想要一个返回枚举值的帮助器方法。所以我理想的帮手方法会更像这样....

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

...并像这样使用它...

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

...但是您无法通过枚举来限制。

解决方案

只有类或接口可以被指定为约束。(c)ReSharper

int(Int32)只是一个结构。你可以限制这个T是结构。但你不能使用任何结构作为约束。



你可以在这里找到的可能的约束列表 - http://msdn.microsoft.com/en-us/library/d5x73970.aspx



UPD



和Enum约束看到这个问题 - 是否有一种针对特殊类的泛型约束的解决方法? Enum in C#3.0?


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. 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. 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

int (Int32) is just a struct. You can constrain that T is a struct. 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

UPD

and for Enum constraint see this question - Is there a workaround for generic type constraint of "special class" Enum in C# 3.0?

这篇关于带整数约束的C#泛型方法拒绝从整型转换为泛型类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆