在Expression <tdelegate>中,TDelegate的参数不是逆变的,方法呢?

时间:2016-02-19 20:47:43

标签: c# generics expression contravariance

我最近遇到了一个问题,处理C#中函数参数的逆变问题,并且只要表达式被该函数包围,它就不会受到尊重。以下是我所谈论的一个例子:

class BaseClass
{
    public bool IsSomething()
    {
        return true;
    }
}

class SubClass : BaseClass { }

static void Main(string[] args)
{
    // This works totally fine
    Func<BaseClass, bool> funcWithBaseClass = item => item.IsSomething();
    Func<SubClass, bool> funcWithSuperClass = funcWithBaseClass;
    var aValidCast = (Func<SubClass, bool>)funcWithBaseClass;

    Expression<Func<BaseClass, bool>> expressionWithBaseClass = item => item.IsSomething();
    // Expression<Func<SubClass, bool>> expressionWithSubClass = expressionWithBaseClass; Get a type mismatch error
    // var invalidCast = (Expression<Func<SubClass, bool>>)expressionWithBaseClass; Invalid cast exception
}

我认为问题必然源于现在Func已经本身成为通用类型参数。

有谁知道我怎么可能绕过这种行为?

1 个答案:

答案 0 :(得分:0)

如果有人好奇,我想出了解决这个问题的方法。我只是做了这样的事情:

getline(input, line);
istringstream iss(line);

int iValue = 0;

iss >> pictureWidth;
iss >> pictureHeight;
iss >> iValue;
pictureColor.Red = iValue;
iss >> iValue;
pictureColor.Green = iValue;
iss >> iValue;
pictureColor.Blue = iValue;