C#对象初始化:从另外一个设置属性 [英] C# Object Initializer : Set Property from another one

查看:267
本文介绍了C#对象初始化:从另外一个设置属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下的对象,其中我在构造函数中我添加了一个新的GUID作为ID。

I have the following object where in my constructor I add a new Guid as the Id.

public class MyObject
{
  public MyObject()
  {
    Id = Guid.NewGuid().ToString();
  }

  public String Id { get; set; }
  public String Test { get; set; }

}



我想要做这样的事情在一个对象初始化

I want to do something like that in an object initializer :

var obj = new MyObject
{
  Test = Id; // Get new GUID created in constructor
}



这可能吗?

Is it possible?

推荐答案

没有,你不能这样做。你必须设置好​​它在一个单独的语句:

No, you can't do that. You'd have to just set it in a separate statement:

var obj = new MyObject();
obj.Test = obj.Id;

在对象初始属性的右侧仅仅是一个正常表达,没有任何内在。连接被初始化的对象。

The right-hand side of the property in an object initializer is just a normal expression, with no inherent connection to the object being initialized.

如果这是你经常要与一个特定类型的做一些事情,你可以添加一个方法:

If this is something you regularly want to do with one specific type, you could add a method:

public MyObject CopyIdToTest()
{
    Test = Id;
    return this;
}



然后使用:

and then use:

MyObject obj = new MyObject().CopyIdToTest();

或与其他属性:

MyObject obj = new MyObject 
{
    // Set other properties here
}.CopyIdToTest();

这篇关于C#对象初始化:从另外一个设置属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆