开发者

Specifying properties when initialising

开发者 https://www.devze.com 2022-12-24 06:27 出处:网络
void Foo() { string ID = \"test\"; var testctrl = new Control() {ID = (ID**!=null?ID**:ID)}; } Is it possible to get the value of ID** in the code above? The开发者_JAVA技巧 problem is they both ha
void Foo()
{

string ID = "test";
var testctrl = new Control() {ID = (ID**!=null?ID**:ID)};

}

Is it possible to get the value of ID** in the code above? The开发者_JAVA技巧 problem is they both have the same property names.

Please ignore the fact the specific ID assignment is pointless, im just using it as an example.


Putting aside that the code can't possibly compile... The first ID (ID=) in this syntax refers to the assignment, specifically the member being assigned. On the right-hand-side, it comes down to standard resolution. Which never means the ID of the new object. It will first look at the local ID variable, then after that members (fields etc) on the current instance. To prefer members on the current instance, use this.ID.

You might also want to consider the null-coalescing operator, so if you mean "the local-variable, or the instance-member if it is null, that would be ID ?? this.ID - but an even better idea would be to make unambiguous variable names ;-p


First remark about this line, it looks strange (assigning string to bool):

bool ID = "test";

Second remark, this works fine:

string ID = "test";
var testctrl = new Control(){ ID = (ID==null?ID:ID) };

Third remark: it is a convention in C# to name your local variables start with lowercase letter.


If you want to check if the new controls id is null then you should do this.

void Foo()
{
    string ID = "test";
    var testctrl = new Control();
    if(testctrl.ID==null)
        testctrl.ID = ID;
}


The question is not that clear to me, but do you want this:

void Foo()
{

bool ID = "test";
var testctrl = new Control(){ID = (this.ID==null?ID:this.ID)};

}

note, untested.


Seeing your example, I suspect that you don't have the requirement that the ID should be unique? In general, to avoid nasty problems like this, avoid try using duplicate property names, but maybe your bound to an existing interface.

How about adding an constructor overload which takes the 'outer' ID as a parameter?

void Foo()
{

string ID = "test";
var testctrl = new Control(ID);

}

I think in general, if the property does more than just assignment (argument checking in this case), you should do it in the 'set' of the property itself and not during 'object initialization'.

0

精彩评论

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