是否可以在c#中创建LOCAL属性(“活动变量”)?

时间:2016-06-03 22:44:56

标签: c# variables

例如,可以通过自动计算生成“活动”全局变量(属性)“区域”:

public int Width = 5;
public int Length = 10;
public int Area
{
   get{ return Width * Length;}
}

但是......是否有可能在这个方法中做出类似的东西 - 局部变量?

1 个答案:

答案 0 :(得分:6)

示例中Area的术语是属性。属性只能在类/结构中声明。

但是,您可以使用lambda(一种特殊的语法来声明一个可以在上下文中捕获变量的函数)来完成类似的事情:

void Method()
{
    int width = 4;
    int length = 2;
    Func<int> area = () => length * width;
    Console.WriteLine("{0}", area());  // 8
    length = 3;
    Console.WriteLine("{0}", area());  // 12
}