是否有可能定义一个局部结构,在方法中,在C#中? [英] Is it possible to define a local struct, within a method, in C#?
问题描述
一个常见的编程的最佳实践是定义变量接近的地方,它们被用作可能的。
One of the common programming best practices is "define variables as close to where they are used as possible".
我用结构经常去创建那几乎是自我记录的地方。然而,C#迫使我定义的方法之外的结构。这打破了上述的最佳实践 - 它基本上是创建一个无用的全局变量类型为整个类
I use structs frequently to create code thats almost self documenting in places. However, C# forces me to define the struct outside the method. This breaks the aforementioned best practice - its basically creating an unwanted global variable type for the entire class.
是否有可能定义一个局部结构的方法里面,就像局部变量,如果没有,你可以给我一个窗户进入的原因,C#设计者决定防止?
Is it possible to define a local struct inside a method, just like a local variable, and if not, could you give me a window into the reasons the C# designers decided to prevent this?
我使用的方法中的结构来存储在一个有组织的方式临时信息,而不必诉诸数百独立变量。我转换部分的电子表格到C#代码。
I'm using the struct within the method to store temporary information in an organized manner, without having to resort to hundreds of separate variables. I'm converting part of a spreadsheet into C# code.
显然,这将是在C#7.0的特征
Apparently, this will be a feature in C# 7.0.
所以C#编译器团队一致 - 哇!
So the C# compiler team agreed - wow!
推荐答案
我相信这是不允许的方法中定义命名类型。至于为什么,我不得不猜测。如果一个类型是不会被外界使用,那么它的存在很可能是没有道理的。
I believe it's not permitted to define named types within a method. As to why, I'll have to speculate. If a type is not going to be used outside, then its existence probably cannot be justified.
但是,您可以定义一个方法中匿名类型的变量。它会有点像结构。妥协。
You can however define anonymous type variables within a method. It will somewhat resembles structures. A compromise.
public void SomeMethod ()
{
var anonymousTypeVar = new { x = 5, y = 10 };
}
这篇关于是否有可能定义一个局部结构,在方法中,在C#中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!