【发布时间】:2015-04-22 23:48:48
【问题描述】:
我遇到的问题是,在下面的示例中,我可以将MyType<T> 转换为IMyType,很好。但是我不能将Func<MyType<T>, bool> 转换为Func<IMyType, bool>。
这没有任何意义,我想知道是否有办法通过不同的架构来解决它?
我不想使用反射。
我也想了解它失败的原因。
.NET 4.5.2 中的代码失败。这里还有在线版本 - http://goo.gl/13z4xg - 以同样的方式失败。
using System;
using System.Collections.Generic;
public interface IMyType
{
string Text { get; }
int Number { get; }
}
public class MyType<T> : IMyType where T : SomeOtherType
{
public MyType()
{
Text = "Hello";
Number = 99;
}
public string Text { get; private set; }
public int Number { get; private set; }
}
public abstract class SomeOtherType
{
public int Id { get; set; }
public string Title { get; set; }
}
public class ConcreteType : SomeOtherType
{
public string Description { get; set; }
}
class Program
{
static void Main(string[] args)
{
var ok = (IMyType) new MyType<ConcreteType>();
Console.Write("I can cast MyType<T> to IMyType here");
var list = new List<Func<IMyType, bool>>();
Func<MyType<ConcreteType>, bool> func = type => false;
// list.Add(func); // Compiler error
list.Add((Func<IMyType,bool>)func); // Runtime cast error
Console.Write("Got here so ok"); // (It doesn't get here...)
}
}
【问题讨论】:
-
您使用的是什么版本的运行时?这并没有给我一个错误(除了由缺少
func名称引起的编译错误)。请注意,这是假设IMyType、MyType、SomeOtherType和ConcreteType : SomeOtherType的定义为空 -
您发布的代码示例“很好”(因为它似乎没有任何方法可以引发您所描述的运行时异常)。你的意思是写
new List<Func<IMyType, bool>>()吗?这将无法以一种易于理解的方式工作(尽管在编译时,而不是运行时)。显然,您还没有发布失败的实际代码。请编辑您的帖子,使其包含可靠地重现问题的a good, minimal, complete code example。 -
@DaxFohl 是的,语法错误
-
@PeterDuniho 显然,我没有发布实际代码,因为如果我这样做了,我显然会丢掉工作。我现在将用一个例子进行编辑。它在运行时确实会失败。
-
重点是,无论您发布什么代码,必须重现您所询问的问题。第一个代码示例没有。通过您的新示例,我发现正如我所猜测的那样,您犯了一个众所周知的错误。 Stack Overflow 上有很多帖子讨论了这个问题;我建议将其作为副本关闭,但由于缺乏好的代码示例,我已经提议关闭它。随意从以下帖子列表中投票关闭作为您最喜欢的副本:stackoverflow.com/q/2033912/3538012,stackoverflow.com/q/8567206/3538012,(继续...)