문제

Given object initializers:

Foo foo = new Foo{ Name = "Jhon", Value = 2, IsMale = true };

Can they be somehow used elsewhere?(outside object construction) So that insted of using:

foo.Name = "Name";
foo.Value = 5;
...
foo.DoSth();

To just use something like:

Name = "Name";
Value = 5;
...
DoSth();

Given that this is outside the class hierarchy of foo. That is to avoid places where you use one object's members many many times.

For example in VB/GML(GameMaker's scripting language) one can use:

with(foo)
{
    Name = "Name";
    Value = 5;
    ...
    DoSth();
}

Instead of foo.something

So is there something like this in C#?

도움이 되었습니까?

해결책

No, object initializer is the only place where assignment syntax like that can be used. If you need to assign multiple fields at once from many different places in code without duplication, you could define a method that encapsulates all the assignments for you:

void SetNameAndGender(string f, string l, bool isMale) {
    FirstName = f;
    LastName = l;
    IsMale = isMale;
}

Unfortunately, it does not let you set an arbitrary group of properties, like the VB syntax that you show.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top