C#:分配相同的值,在单个语句多个变量 [英] C#: Assign same value to multiple variables in single statement

查看:137
本文介绍了C#:分配相同的值,在单个语句多个变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么办法(只是出于好奇,因为我今天跨越多个同一值分配给多个变量来)在C#一次在一个单一的语句来分配一个值,以多个变量?

Is there any way (just out of curiosity because I came across multiple same-value assignments to multiple variables today) in C# to assign one value to multiple variables at once in a single statements?

沿着这些东西线(伪code):

Something along these lines (pseudocode):

int num1 = 1;
int num2 = 1;

num1 & num2 = 5;

或许不会,但我想我是值得一问的类似案件的东西其实是可以的!

Probably not but I thought i was worth asking in case something similar is actually possible!

推荐答案

这是简单:

num1 = num2 = 5;

当使用一个对象的属性,而不是变量,有趣的是要知道,中间值的 GET 访问不叫。只有访问器在分配顺序访问的所有属性。

When using an object property instead of variable, it is interesting to know that the get accessor of the intermediate value is not called. Only the set accessor is invoked for all property accessed in the assignation sequence.

举个例子,写入控制台每次的 GET 设置访问被调用的类。

Take for example a class that write to the console everytime the get and set accessor are invoked.

static void Main(string[] args)
{
    var accessorSource = new AccessorTest(5);
    var accessor1 = new AccessorTest();
    var accessor2 = new AccessorTest();

    accessor1.Value = accessor2.Value = accessorSource.Value;

    Console.ReadLine();
}

public class AccessorTest
{
    public AccessorTest(int value = default(int))
    {
        _Value = value;
    }

    private int _Value;

    public int Value
    {
        get
        {
            Console.WriteLine("AccessorTest.Value.get {0}", _Value);
            return _Value;
        }
        set
        {
            Console.WriteLine("AccessorTest.Value.set {0}", value);
            _Value = value;
        }
    }
}

这将输出

AccessorTest.Value.get 5
AccessorTest.Value.set 5
AccessorTest.Value.set 5

这意味着编译器将值分配给所有属性和它不会每次分配时重新读取的值。

Meaning that the compiler will assign the value to all properties and it will not re-read the value every time it is assigned.

这篇关于C#:分配相同的值,在单个语句多个变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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