C# 在运行时动态转换泛型对象
编辑:将错误的术语“拳击”更改为“铸造”。
我有以下问题:
如果我创建一个 Action 或 Func 类型的新委托,它将被转换为 Delegate 类型。
var @delegate = Delegate.CreateDelegate(type, @object, methodInfo);
但我需要一个通用类和正确的铸造对象。
考虑以下示例:
class Example<T> {
Type GenericType() {
return typeof(T);
}
}
static Example<T> Create<T>(T @delegate) {
return new Example<T>();
}
Example.Create(@delegate).GenericType();
这将返回 Delegate 作为类型,因为这是转换对象 (@delegate) 的类型。
一种解决方案可能是像这样转换委托:
if(@delegate is Action)
Example.Create((Action)@delegate).GenericType();
但由于 Delegate.CreateDelegate 也可以创建 Action 或 Func 委托,因此不可能检查所有变体。
我无法更改通用类,因此我必须强制转换委托。
我希望我能够解释我的问题。我不是以英语为母语的人...
编辑:问题是 typeof(T) 不返回对象的“真实”类型。但恐怕没有解决办法。
Edit: Changed the wrong term boxing to casting.
I have the following problem:
If I create a new Delegate of type Action or Func it will be casted to a type of Delegate.
var @delegate = Delegate.CreateDelegate(type, @object, methodInfo);
But I need for a generic class the right casted object.
Consider following example:
class Example<T> {
Type GenericType() {
return typeof(T);
}
}
static Example<T> Create<T>(T @delegate) {
return new Example<T>();
}
Example.Create(@delegate).GenericType();
This will return Delegate as type, since this was the type of the casted object (@delegate).
One solution could be to cast the delegate like so:
if(@delegate is Action)
Example.Create((Action)@delegate).GenericType();
But since Delegate.CreateDelegate could also create Action or Func delegates, it is impossible to check all variations.
I can't change the generic class, so i must cast the delegate.
I hope i was able to explain my problem. I am not a native English speaker...
Edit: The Problem is that typeof(T) not return the "real" type of the object. But i'm afraid there is no solution.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用
@delegate.GetType()
获取委托的实际类型有什么问题?另外,附注:您误用了“拳击”一词。
What's wrong with
@delegate.GetType()
to get the actual type of the delegate?Also, a side note: you are misusing the term "boxing".
如果你可以使用.net 4.0,那么你的上面的工作如果你转换为动态的话
,如果你不能,那么你只需要做一些反射和抽象。
If you can use .net 4.0 then your above works if you cast to dynamic
If you cannot, then you just have to do a little reflection and abstraction.
回答我自己的问题:这是不可能的。 :(
To answer my own question: It is not possible. :(