C#枚举协方差不起作用 [英] c# enum covariance doesn't work
问题描述
我需要使用enum作为协变类型.假设我有以下代码:
I need to use enum as covariant type. Let's say i have this code:
public enum EnumColor
{
Blue = 0,
Red = 1,
}
public class Car : IColoredObject<EnumColor>
{
private EnumColor m_Color;
public EnumColor Color
{
get
{
return m_Color;
}
set
{
m_Color = value;
}
}
public Car()
{
}
}
class Program
{
static void Main()
{
Car car = new Car();
IndependentClass.DoesItWork( car );
}
}
和此代码:
public interface IColoredObject<out EnumColorType>
{
EnumColorType Color
{
get;
}
}
public static class IndependentClass
{
public static void DoesItWork( object car )
{
IColoredObject<object> coloredObject = car as IColoredObject<object>;
if( coloredObject == null )
Console.WriteLine( "It doesn't work." );
else
{
Console.WriteLine( "It works." );
int colorNumber = (int)( coloredObject.Color );
Console.WriteLine( "Car has got color number " + colorNumber + "." );
}
}
}
我正在尝试使用Enum.
I was trying to use Enum.
IColoredObject<Enum> coloredObject = car as IColoredObject<Enum>;
我试图使用IConvertible,它是Enum的接口.
I was trying to use IConvertible which is interface of Enum.
IColoredObject<IConvertible> coloredObject = car as IColoredObject<IConvertible>;
但是每次都行不通(它为空).
But everytime it doesn't work (it was null).
我应该使用什么?或者我该怎么办?
What should i use ? Or how can i do it ?
(我不想在代码的第二部分中使用EnumColor,因为我希望两个独立的代码仅通过接口连接.)
(I don't want to use EnumColor in second part of code, because i want two independent codes joined only with interface.)
推荐答案
值类型"不支持协方差.枚举
属于此类别,因此不起作用.
Covariance is not supported with "Value types" Enum
falls under this category and hence doesn't work.
仅引用类型支持通用接口中的差异.值类型不支持方差.例如,
IEnumerable< int>
(Visual Basic中的IEnumerable(In Integer))不能隐式转换为IEnumerable< object>
(Visual Studio中的IEnumerable(Of Object)基本),因为整数由值类型表示.
Variance in generic interfaces is supported for reference types only. Value types do not support variance. For example,
IEnumerable<int>
(IEnumerable(Of Integer) in Visual Basic) cannot be implicitly converted toIEnumerable<object>
(IEnumerable(Of Object) in Visual Basic), because integers are represented by a value type.
这篇关于C#枚举协方差不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!