如何将 void 返回扩展方法传递给动态返回扩展方法?
我想将一个返回 void 作为参数的扩展方法传递给另一个返回动态的扩展方法。
public static void AddTo(this Object entity, Object parent)
{
parent.GetCollectionOf(entity).Add(entity);
}
public static dynamic And(this Object entity, Action method)
{
entity.method(parent);
return entity;
}
我想像这样使用它,
dynamic parent = MakeNew(parentType);
dynamic entity = MakeNew(type).And(AddTo(parent));
我喜欢将任何 void 方法传递给 And()
但仍然返回它扩展的对象。我希望动态返回类型没有问题。
这种事情的语法是什么?
I want to pass an extension method that returns void as a parameter to another extension method that returns dynamic.
public static void AddTo(this Object entity, Object parent)
{
parent.GetCollectionOf(entity).Add(entity);
}
public static dynamic And(this Object entity, Action method)
{
entity.method(parent);
return entity;
}
I'd like to use it something like this,
dynamic parent = MakeNew(parentType);
dynamic entity = MakeNew(type).And(AddTo(parent));
I like to pass any void method into And()
but still return the object it extended. I hope the dynamic return type is not problematic.
What is the syntax for this kind of thing?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我问你的问题正确吗?
Have I got your question right?
你可以这样做吗?
小心使用我的 linq,它随时可能爆炸;-)
为了充分解释这一点:
Could you perhaps do it like this?
Use my linq carefully, it could explode at any moment ;-)
To explain this fully:
我认为 C# 还不够“动态”,无法完成我认为您想要的事情。
And 方法将不起作用,因为
entity
参数的类型为object
,因此entity.method(parent)
将不起作用。即使您将entity
定义为dynamic
类型,C# 也会尝试找到一个名为“method”的方法来调用。您可以在您的示例中执行此操作:和
I think that C# is not yet "dynamic" enough to do the thing I think you want.
The And method won't work, since the
entity
parameter is of typeobject
, soentity.method(parent)
will not work. Even if you defineentity
to be of typedynamic
, C# will try to find a method called "method" to call. You can do this in your example:and
我怀疑你实际上想要这个:
话虽如此,但仍然不清楚
parent
从哪里开始......I suspect you actually want this:
Having said that, it's still not clear where
parent
is coming from to start with...