【发布时间】:2020-04-27 08:24:29
【问题描述】:
在 nodejs/typescript 编程后开始学习 c#。
我遇到了以下错误:
TypeTests.cs(22,50):错误 CS1061:“Book”不包含“name”的定义,并且找不到接受“Book”类型的第一个参数的可访问扩展方法“name”(你是缺少 using 指令或程序集引用?)
这是我的课
using System;
using System.Collections.Generic;
namespace GradeBook
{
public class Book
{
// this is how we generate a constructor in c#
public Book(string name)
{
grades = new List<double>();
Name = name;
}
public void AddGrade(double grade)
{
grades.Add(grade);
Console.WriteLine($"A new added grade: {grade:N2}");
}
public Stats GetStats()
{
var result = new Stats();
result.Average = 0.0;
result.High = double.MinValue;
result.Low = double.MaxValue;
foreach (var grade in grades)
{
// log hightest grades
result.High = Math.Max(grade, result.High);
// log lowest grades
result.Low = Math.Min(grade, result.Low);
result.Average += grade;
}
result.Average /= grades.Count;
return result;
}
// its no longer a variable it is now called field in c#
private List<double> grades;
public string Name;
}
}
我的测试课:
using System;
using Xunit;
namespace GradeBook.tests
{
/*
// Guideline to writing good unit tests:
// arrange the test
// act - the actual actions
// assert - the values that are computed in the act section
*/
public class TypeTests
{
[Fact]
public void CSharpIsPassByValue()
{
// arrange
var book1 = GetBook("My Book");
GetBookSetName(book1, "New Book Name!");
//assert
Assert.Equal("My Book", book1.name);
}
private void GetBookSetName(Book book, string name)
{
book = new Book(name);
}
[Fact]
public void CanSetNameFromReference()
{
// arrange
var book1 = GetBook("My Book");
SetName(book1, "New Book Name!");
//assert
Assert.Equal("New Book Name!", book1.name);
}
private void SetName(Book book, string name)
{
book.Name = name;
}
[Fact]
public void GetBookReturnsDifferentObjects()
{
// arrange
var book1 = GetBook("My Book");
var book2 = GetBook("My Other Book");
//assert
Assert.Equal("My Book", book1.name);
Assert.Equal("My Other Book", book2.name);
Assert.NotSame(book1, book2);
}
[Fact]
public void TwoVarsCanReferenceSameObject()
{
var book1 = GetBook("Book 1");
var book2 = book1;
Assert.Same(book1, book2);
Assert.True(Object.ReferenceEquals(book1, book2));
}
Book GetBook(string name)
{
return new Book(name);
}
}
}
【问题讨论】:
-
代码的哪一行抛出异常?