Mat*_*dge 20 c# coding-style dynamic c#-4.0
我的问题是下面是否适当使用dynamicC#4 中的关键字.
我有一些辅助方法,它们提供了比标准ToString方法更有用的各种对象表示,我用它来进行单元测试.这是一个简化的例子:
public static string PrettyPrint<T>(IEnumerable<T> list)
{
return string.Join(", ", list);
}
// Needed because string is IEnumerable<char>, to prevent
// "Hello" -> "H, e, l, l, o"
public static string PrettyPrint(string s)
{
return s;
}
public static string PrettyPrint(object o)
{
return o.ToString();
}
Run Code Online (Sandbox Code Playgroud)
我用它们是这样的:
public static void PrettyPrinting()
{
object[] things = { 1, "Hello", new int[] {1, 2, 3} };
foreach (dynamic item in things)
{
Console.WriteLine(PrettyPrint(item));
}
}
Run Code Online (Sandbox Code Playgroud)
这会产生以下输出:
1
Hello
1, 2, 3
Run Code Online (Sandbox Code Playgroud)
请注意,如果我将dynamic关键字替换为object,我会得到以下内容(所有调用都被路由通过PrettyPrint(object)),这就是我要避免的:
1
Hello
System.Int32[]
Run Code Online (Sandbox Code Playgroud)
所以我的问题基本上是代码气味或object以dynamic这种方式投射到它是合法的吗?