开发者

Anonymous types syntax

I know we can use such syntax

var r = new MyType { name = "dd"}

Is it possible to have such开发者_JAVA百科 syntax in any simpler way

MyType myType = GetMyType("some method returns instance of mytype"){
       name="myname", 
       otherProp = otherPro, 
       ExecuteMyTypeMethod()
    };


Note that what you've shown are not anonymous types, which are like this:

var r = new { name = "dd" }; // Note the lack of a type name

This is object initializer syntax - and no, it only works with constructors. I've occasionally found that a pain too, but that's the way it is.

EDIT: A comment suggested using extension methods. You could do this:

public static T With<T>(this T item, Action<T> action) where T : class
{
    action(item);
    return item;
}

at which point you could write:

MyType myType = GetMyType("some method returns instance of mytype").With(t => {
   t.name="myname";
   t.otherProp = otherPro;
   t.ExecuteMyTypeMethod();
});

The only benefit of this is that you can still perform the initialization in a single experssion. Usually I'd prefer to just use separate statements.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜