小编Hat*_*ing的帖子

如何在没有装箱的情况下比较System.Enum和枚举(实现)?

我如何可以比较System.Enum一个enum没有拳击?例如,如何在不装箱的情况下使下面的代码工作enum

enum Color
{
    Red,
    Green,
    Blue
}

...

System.Enum myEnum = GetEnum(); // Returns a System.Enum. 
                                // May be a Color, may be some other enum type.

...

if (myEnum == Color.Red) // ERROR!
{
    DoSomething();
}
Run Code Online (Sandbox Code Playgroud)

具体而言,此处的目的不是比较基础值.在这种情况下,基础值并不重要.相反,如果两个枚举具有相同的基础值,则如果它们是两种不同的枚举,则不应将它们视为相等:

enum Fruit
{
    Apple = 0,
    Banana = 1,
    Orange = 2
}

enum Vegetable
{
    Tomato = 0,
    Carrot = 1,
    Celery = 2
}

myEnum = Vegetable.Tomato;
if (myEnum != Fruit.Apple) // ERROR! …
Run Code Online (Sandbox Code Playgroud)

c# enums

12
推荐指数
1
解决办法
1108
查看次数

与接口的通用协方差 - "是"和"="运算符之间奇怪的行为矛盾

在处理协变接口时,我有一个完整的wtf时刻.

考虑以下:

class Fruit { }
class Apple : Fruit { }

interface IBasket<out T> { }

class FruitBasket : IBasket<Fruit> { }
class AppleBasket : IBasket<Apple> { }
Run Code Online (Sandbox Code Playgroud)

注意:

  • AppleBasket 不继承自 FruitBasket.
  • IBasket协变的.

稍后在脚本中,您写道:

FruitBasket fruitBasket = new FruitBasket();
AppleBasket appleBasket = new AppleBasket();

Log(fruitBasket is IBasket<Fruit>);
Log(appleBasket is IBasket<Apple>);
Run Code Online (Sandbox Code Playgroud)

......正如您所期望的那样,输出是:

true
true
Run Code Online (Sandbox Code Playgroud)

但是,请考虑以下代码:

AppleBasket appleBasket = new AppleBasket();

Log(appleBasket is IBasket<Fruit>);    
Run Code Online (Sandbox Code Playgroud)

你期望它输出true,对吗?好吧,你错了 - 至少我的编译器是这样的:

false    
Run Code Online (Sandbox Code Playgroud)

这很奇怪,但也许它正在执行隐式转换,类似于将inta …

c# generics casting interface covariance

5
推荐指数
1
解决办法
155
查看次数

泛型 - 实现相互编译时类型安全的更清洁方式?

假设你有一个由"父母"和"孩子"组成的数据结构,父母和孩子之间的引用是相互的:

借用前一篇文章,编写以下代码以保证父母与子女之间的相互参照(不包括滥用反思):

public static class Base
{
    private interface IParent
    {
        List<Child> Children { get; }
    }

    public class Parent : IParent
    {
        private readonly List<Child> _children = new List<Child>();

        public readonly ReadOnlyCollection<Child> Children = _children.AsReadOnly();

        List<Child> IParent.Children { get { return _children; } }
    }

    public class Child
    {
        private Parent _parent;

        public Parent Parent
        {
            get
            {
                return _parent;
            }
            set
            {
                if(value == _parent)
                    return;

                if(_parent != null)
                {
                    ((IParent)_parent).Children.Remove(this);
                    _parent = null; …
Run Code Online (Sandbox Code Playgroud)

c# generics type-safety

0
推荐指数
1
解决办法
241
查看次数

标签 统计

c# ×3

generics ×2

casting ×1

covariance ×1

enums ×1

interface ×1

type-safety ×1