【发布时间】:2017-01-01 12:30:05
【问题描述】:
我使用从DynamicObject 派生的类型作为某些字符串的构建器。最后我调用ToString 得到最终结果。
此时我认为它会给我一个正常的字符串,但这个字符串有点奇怪。当我在其上使用字符串函数时,它的行为就像一个,但它的行为就像我不知道实际上是什么,既不是字符串也不是动态的。
这就是我在构建器上实现ToString 的方式
public class Example : DynamicObject
{
public override bool TryConvert(ConvertBinder binder, out object result)
{
if (binder.ReturnType == typeof(string))
{
result = ToString();
return true;
}
result = null;
return false;
}
public override string ToString()
{
return base.ToString();
}
}
当我这样运行时
dynamic example = new Example();
Console.WriteLine(example.ToString().ToUpper());
结果正确:USERQUERY+EXAMPLE(在 LINQPad 中执行时)
但是,如果我这样调用第二行
Console.WriteLine(example.ToString().Extension());
在哪里
static class Extensions
{
public static string Extension(this string str)
{
return str.ToUpper();
}
}
应用程序因RuntimeBinderException 而崩溃
“字符串”不包含“扩展”的定义
但如果我转换结果,它会再次起作用
Console.WriteLine(((string)example.ToString()).Extension());
也许还有一个例子。
Console.WriteLine((string)example); // UserQuery+Example
但是
Console.WriteLine(example); // DynamicObject UserQuery+Example
在将其转换为字符串之前,您实际上永远无法确定会得到什么。
为什么会发生这种情况,有没有办法避免额外的演员表并以某种方式获得 real 字符串?
【问题讨论】: