Zin*_*nov 1 c# c#-4.0 dynamictype
嗨,我有一个包含很多类的命名空间,所有这些都有一个方法Destroy(int id)我想用动态词调用该方法.
这是我的例子:
public bool DeleteElement<T>(T tElement)
{
Type t = typeof(T);
dynamic element = tElement;
var id = element.Id;
//until here everything is fine
//here I want to say
(namespace).myClassName.Destroy(id);
//the name of myClassName is like t.ToString()
}
Run Code Online (Sandbox Code Playgroud)
我可以避免命名空间,包括在顶部使用.我的想法是使用动态调用静态方法,而不是反射,请看Destroy是T的静态方法.我需要像这样的东西T.Destroy(id)
如果Destroy(int id)是静态方法,你不能创建一个可以调用静态方法的实例方法吗?
public void Destroy()
{
ThisClass.Destroy(this.Id);
}
Run Code Online (Sandbox Code Playgroud)
然后,您可以定义IDestroyable由所有这些类实现的接口:
interface IDestroyable { void Destroy(); }
Run Code Online (Sandbox Code Playgroud)
然后修改您的DeleteElement方法如下:
public bool DeleteElement<T>(T tElement) where T : IDestroyable
{
tElement.Destroy();
}
Run Code Online (Sandbox Code Playgroud)
不需要在dynamic这里使用......实际上,dynamic在这种情况下使用往往表明设计不好.除了在创建它的场景中,实际需要 它是非常罕见的dynamic(例如,与动态语言互操作)
(如果生成了类但它们具有partial修饰符,则可以在另一个未被生成器触及的文件中声明新方法)
编辑:如果类是生成的而不是partial,则无法修改它们......所以另一种解决方案是使用反射; 我知道你想避免(因为性能原因我认为),但你可以限制通过做反射一次为每种类型的性能影响:你只需要创建和缓存的委托对每种类型.
class DestroyHelper<T>
{
static readonly Action<int> _destroy;
static readonly Func<T, int> _getId;
static DestroyHelper()
{
var destroyMethod = typeof(T).GetMethod("Destroy", BindingFlags.Static | BindingFlags.Public);
_destroy = (Action<int>)Delegate.CreateDelegate(typeof(Action<int>), destroyMethod);
var getIdMethod = typeof(T).GetProperty("Id").GetGetMethod();
_getId = (Func<T, int>)Delegate.CreateDelegate(typeof(Func<T, int>), getIdMethod);
}
public static void Destroy(T element)
{
_destroy(_getId(element));
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
78 次 |
| 最近记录: |