0

嘿,我是 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);

    }
}
4

2 回答 2

6

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

例如

public class Invoice
{
    public int ID { get; set; }
    public string Description { get; set; }
    public decimal Amount { get; set; }
}
于 2012-06-11T12:10:22.147 回答
1

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

SomeProperty { get; set; } 

这相当于去:

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

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

 SomeProperty ( get; set; )

对口译员意义不大

您知道 Visual Studio 中有一些代码片段可以为您执行此操作:

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

于 2012-06-11T12:16:23.760 回答