C#:为什么设计团队决定不允许在标识符中使用空格?

时间:2016-05-24 19:43:01

标签: c# asp.net .net

在Visual Basic中,您可以使用以下语法:

Dim [My variable with spaces]
[My variable with spaces] = 9000

在SQL Server中:(我意识到这与C#无关,只是用作语法示例)

create table [My Table With Spaces](
[My Column With Spaces] varchar(30) null)

我的问题是,为什么这种语法永远不会被纳入C#?

我知道人们可能会认为这很愚蠢,很少会被使用,在标识符等中使用空格是不好的做法。嗯,如果它在Visual Basic中有支持,那么它一定不是那么糟糕的练习SQL Server。 在C#中它会立即解决友好的枚举问题。现在大多数解决方案都涉及使用DescriptionAttribute:

public enum UnitedStates
{
    [Description("Alabama")]
    Alabama,
    //...
    [Description("New Hampshire")]
    NH,
    //...
    [Description("Wyoming")]
    Wyoming
}
public static class Extensions
{
    public static string GetDescription(this Enum self)
    {
        //tedious, inefficient reflection stuff...
    }
}

这不仅需要比预期更多的代码,而且在数据绑定中使用ToString()的ASP.NET数据绑定方法失败了。例如:

public class Person
{
    public string Name { get; set; }
    public UnitedStates FavoriteState { get; set; }
}

这在ASPX中:

<asp:GridView ID="myGridView" runat="server">
    <Columns>
        <asp:BoundField DataField="Name" HeaderText="Name" />
        <asp:BoundField DataField="FavoriteState" HeaderText="Favorite State" /><%--NO!--%>
    </Columns>
</asp:GridView>

正如您所看到的,DescriptionAttribute看起来越来越不健壮。现在考虑以下内容:

public enum UnitedStates
{
    Alabama,
    //...
    [New Hampshire],
    //...
    Wyoming
}
var myFavoriteState = UnitedStates.[New Hampshire];
string str = myFavoriteState.ToString(); // YES!

从我所看到的,MSIL中定义的程序集支持名称中包含空格的字段,属性,变量等。例如,使用System.Reflection.Emit:

创建程序集时
AssemblyName assemblyName = new AssemblyName("TestModule");
AssemblyBuilder assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Save);
ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("TestModule", "TestModule.dll");
TypeBuilder typeBuilder = moduleBuilder.DefineType("MyType", TypeAttributes.Public | TypeAttributes.BeforeFieldInit);
typeBuilder.DefineField("My field with spaces", typeof(int), FieldAttributes.Public);
EnumBuilder usEnum = moduleBuilder.DefineEnum("UnitedStates", TypeAttributes.Public, typeof(int));
usEnum.DefineLiteral("Alabama", 0);
usEnum.DefineLiteral("New Hampshire", 1);
usEnum.CreateType();
typeBuilder.CreateType();
assemblyBuilder.Save("TestModule.dll");

这样可以创建一个工作程序集。所以在我看来,在语法中添加支持将是相对无缝的。我发现的另一个问题是Visual Studio intellisense不显示包含空格的公共成员。

虽然这看起来像是一个愿望列表而不是问题,但我只是想知道为什么设计师决定将这种支持提供给Visual Basic而不是C#。

0 个答案:

没有答案
相关问题