[英]C# method syntax similar to object initializer
We have an extension method that accepts an action to initialize an object.我们有一个扩展方法,它接受一个初始化 object 的操作。 Is there some way to improve the syntax of such a call:
有没有办法改进这种调用的语法:
public static T NewRow<T>(this IUow uow, Action<T> action();
// this does internally call
public T NewRow<T>(Action<T> initializer) where T : IBo
{
T bo = NewRow<T>();
initializer.Invoke(bo);
return bo;
}
uow.NewRow<ICustomer>(customer => {
customer.Name = "Zzz";
customer.Info = "Abc"
);
I thought maybe I could use something similar to the object initializer syntax?我想也许我可以使用类似于 object 初始化器语法的东西?
uow.NewRow<ICustomer>({
Name: "Zzz",
Info: "Abc"
});
The idea is to get rid of customer.* =...
in every line.这个想法是在每一行中摆脱
customer.* =...
I would be happy for any tip.我会很高兴任何提示。
INFO:信息:
Edit:编辑:
T bo = NewRow<T>();
T bo = NewRow<T>();
. { Name: myOtherVariable.FirstName }
should be possible{ Name: myOtherVariable.FirstName }
这样的初始化程序也应该是可能的an Action
could be everything , not just a simple assignment.一个
Action
可以是一切,而不仅仅是一个简单的分配。 So if a client chosed to make a function-call instead, there literally is nothing to shortcut here.因此,如果客户选择进行函数调用,那么这里实际上没有什么可以捷径的。 See this for example:
例如看这个:
uow.NewRow<IWhatever>(() => Console.WriteLine("tataaaa"););
So no, what you want isn't possible.所以不,你想要的是不可能的。
However you could create some kind of EventsArgs
that hold your names and use those within your NewRow
-method.但是,您可以创建某种
EventsArgs
来保存您的姓名并在您的NewRow
方法中使用这些名称。 There's no need for an action if all those callbacks should actually be just assignement-calls alltogether.如果所有这些回调实际上应该只是全部的赋值调用,则无需执行任何操作。
uow.NewRow<ICustomer>(new MyArgs {
Name = "Zzz",
Info = "Abc"
});
And within NewRow
:在
NewRow
内:
public T NewRow<T>(MyArgs args) where T : IBo
{
customer.Name = args.Name;
customer.Info = args.Info;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.