在dynamic泛型类上实现动态分派,并且泛型类型参数是另一个类上的私有内部类时,运行时绑定程序会引发异常.
例如:
using System;
public abstract class Dispatcher<T> {
public T Call(object foo) { return CallDispatch((dynamic)foo); }
protected abstract T CallDispatch(int foo);
protected abstract T CallDispatch(string foo);
}
public class Program {
public static void Main() {
TypeFinder d = new TypeFinder();
Console.WriteLine(d.Call(0));
Console.WriteLine(d.Call(""));
}
private class TypeFinder : Dispatcher<CallType> {
protected override CallType CallDispatch(int foo) {
return CallType.Int;
}
protected override CallType CallDispatch(string foo) {
return CallType.String;
}
}
private enum CallType { Int, String }
} …Run Code Online (Sandbox Code Playgroud) 我在Fabio Maulo的博客上看过一篇非常有趣的帖子.如果您不想跳转到网址,这是代码和错误.我定义了一个新的泛型类,如下所示:
public class TableStorageInitializer<TTableEntity> where TTableEntity : class, new()
{
public void Initialize()
{
InitializeInstance(new TTableEntity());
}
public void InitializeInstance(dynamic entity)
{
entity.PartitionKey = Guid.NewGuid().ToString();
entity.RowKey = Guid.NewGuid().ToString();
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,InitializeInstance接受一个参数,该参数的类型为dynamic.现在要测试这个类,我定义了另一个嵌套在我的主Program类中的类,如下所示:
class Program
{
static void Main(string[] args)
{
TableStorageInitializer<MyClass> x = new TableStorageInitializer<MyClass>();
x.Initialize();
}
private class MyClass
{
public string PartitionKey { get; set; }
public string RowKey { get; set; }
public DateTime Timestamp { get; set; }
}
}
Run Code Online (Sandbox Code Playgroud)
注意:内部类"MyClass"被声明为私有.
现在,如果我运行此代码,我会在"entity.PartitionKey = Guide.NewGuid().ToString()"行中获得 …