下面的代码引发异常。没有为转换接口调用TryConvert。为什么会这样呢?我能解决这个问题吗?
using System.Dynamic;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
dynamic test = new JsonNull();
var ok = (string)test;
// Next line throws:
// Unable to cast object of type 'ConsoleApplication1.JsonNull' to type 'ConsoleApplication1.IFoo'.
var fail = (IFoo)test;
}
}
class JsonNull : DynamicObject
{
public override bool TryConvert(ConvertBinder binder, out object result)
{
result = null;
return !binder.Type.IsValueType;
}
}
interface IFoo { }
}
发布于 2011-01-25 05:31:12
我发现如果你改变这一行:
var fail = (IFoo)test;
要这样做:
IFoo success = test;
它的工作方式与预期一致。
在这种情况下,似乎只有隐式转换有效。在我看来像是个虫子。
我还发现这也失败了,这是非常恼人的:
class Program {
static void Main(string[] args) {
dynamic test = new JsonNull();
Fails(test);
}
static void Fails(IFoo ifoo) { }
}
// ...
因为它看起来也应该使用隐式转换。又是一个bug?
https://stackoverflow.com/questions/3492955
复制相似问题