简体   繁体   English

C# 方法语法类似于 object 初始化程序

[英]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:信息:

  • We are using the latest C# language version我们使用的是最新的C#语言版本
  • The solution should support IntelliSense (eg, Name and Info should be proposed to the user)解决方案应支持 IntelliSense(例如,应向用户建议名称和信息)

Edit:编辑:

  • I can't use a constructor because I only have an interface.我不能使用构造函数,因为我只有一个接口。 No class/implementation.没有类/实现。 The framework behind creates the object to the given interface T bo = NewRow<T>();后面的框架创建 object 到给定的接口T bo = NewRow<T>(); . . Which actual object gets created is decided by the framework实际创建的 object 由框架决定
  • Also initializers like { 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM