【问题标题】:Identifier expected c#标识符预期 c#
【发布时间】:2012-06-11 12:09:39
【问题描述】:

嘿,我是 C# 新手,我正在学习一个教程,但我的代码中出现错误...它在到达此处 (get;set;) 时显示“预期标识符”,并且还给出错误“无效令牌';'在类、结构或接口成员声明中”在集合中。

任何帮助都将不胜感激。

谢谢!!

public class Invoice
{
    public int ID ( get; set; )
    public string Description ( get; set; )
    public decimal Amount ( get; set; )
}


[TestClass]
public class ReferenceTypesAndValueTypes
{
    [TestMethod]
    public void IdentityTest()
    {
        Invoice firstInvoice = new Invoice();
        firstInvoice.ID = 1;
        firstInvoice.Description = "Test";
        firstInvoice.Amount = 0.0M;

        Invoice secondInvoice = new Invoice();
        secondInvoice.ID = 1;
        secondInvoice.Description = "Test";
        secondInvoice.Amount = 0.0M;

        Assert.IsFalse(object.ReferenceEquals(secondInvoice, firstInvoice));
        Assert.IsTrue(firstInvoice.ID == 1);

        secondInvoice.ID = 2;

        Assert.IsTrue(secondInvoice.ID == 2);
        Assert.IsTrue(firstInvoice.ID == 1);

        secondInvoice = firstInvoice;

        Assert.IsTrue(object.ReferenceEquals(secondInvoice,firstInvoice));

        secondInvoice.ID = 5;
        Assert.IsTrue(firstInvoice.ID == 5);

    }
}

【问题讨论】:

    标签: c# identifier


    【解决方案1】:

    你需要用大括号{}替换括号()

    例如

    public class Invoice
    {
        public int ID { get; set; }
        public string Description { get; set; }
        public decimal Amount { get; set; }
    }
    

    【讨论】:

    • 大声笑我正要评论“哪里”:P很高兴你编辑了
    【解决方案2】:

    在 auto 属性中,语法糖允许您省略 getter/setter 的实现 - 所以您应该有这个:

    SomeProperty { get; set; } 
    

    相当于去:

    SomeProperty 
    { 
       get { return _somePropertyBackingField; }
       set { _somePropertyBackingField = value; }
    }
    

    这些都不需要括号,因为这是结构符号 - 括号通常保留用于转换和方法调用

     SomeProperty ( get; set; )
    

    对解释器来说意义不大

    您知道 Visual Studio 中有代码 sn-ps 可以为您执行此操作:

    只需键入“prop”并按两次制表符。试试看 :) - 不再有错别字

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-07
      • 2011-12-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多