我使用从 DynamicObject 派生的类型作为某些字符串的构建器。最后,我致电 ToString 以获得最终结果。
I use a type derived from a DynamicObject as a builder for some strings. At the end I call ToString to get the final result.
在这一点上,我认为这会给我一个正常的字符串,但是这个字符串有点奇怪。当我在其上使用字符串函数时,它的行为就像一个,但实际上却不知道是什么,既不是字符串也不是动态的。
At this point I thought it would give me a normal string but this string is somehow strange. It behaves like one when I use string functions on it but it behaves like I don't know actually what, something neither a string nor a dynamic.
这是我在生成器上实现 ToString 的方式
This is how I implemented ToString on my builder
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中执行时)
the result is correct: USERQUERY+EXAMPLE (when executed in LINQPad)
但是如果我这样叫第二行
However if I call the second line like this
Console.WriteLine(example.ToString().Extension());其中
static class Extensions { public static string Extension(this string str) { return str.ToUpper(); } }应用程序因而崩溃RuntimeBinderException 说
字符串不包含扩展的定义
'string' does not contain a definition for 'Extension'
但是如果我强制转换结果,它将再次起作用
but if I cast the result it works again
Console.WriteLine(((string)example.ToString()).Extension());
也许还有一个例子。
Maybe one more example.
Console.WriteLine((string)example); // UserQuery+Example但是
Console.WriteLine(example); // DynamicObject UserQuery+Example实际上,在转换之前,您永远无法确定会得到什么
You can actually never be sure what you'll get until you cast it to string.
为什么会这样,有没有办法避免额外的转换并以某种方式获取真正的字符串?
Why is this happening and is there a way to avoid the additional cast and get somehow a real string?
推荐答案这是因为调用了 ToString 键入 dynamic 返回 dynamic 而不返回 string :
That's because ToString called on dynamic is typed to return dynamic and not string:
dynamic example = new Example(); // test will be typed as dynamic var test = example.ToString();当您在<$ c上呼叫 ToUpper 时$ c> test 它将使用动态绑定并在运行时解析为 string.ToUpper 。您必须将具体类型转换为转义动态类型。
When you call ToUpper on test it will use dynamic binding and resolve to string.ToUpper at runtime. You have to cast to a concrete type to escape dynamic typing.
扩展方法是编译时功能,因此 dynamic 不输入扩展名,因此不支持方法。您仍然可以使用常规的静态方法调用语法来调用它。
Extension methods is a compile-time feature and as such is not supported by dynamic typing as extension method. You can still call it using regular static method invocation syntax.
Extensions.Extension(example.ToString());但是再次- example.ToString()将返回 dynamic 并在运行时进行类型绑定,以检查它是否可以用作 Extensions.Extension 的参数呼叫。查看此答案以了解详细信息。
But again - example.ToString() will return dynamic and type binding will happen at runtime to check if it can be used as a parameter to Extensions.Extension call. Check this answer for details.
更多推荐
为什么dynamic.ToString()在字符串而不是字符串之间返回某些内容?
发布评论