错误 CS0119; class 是一种类型,在给定上下文中无效
Error CS0119; class is a type, which is not valid in the given context
熟悉 C# 后,在进行断言的行上进行单元测试时出现以下错误 Assert.IsInstanceTypeOf
。
Error CS0119 'Product' is a type, which is not valid in the given context
创建类型的事情已经完成。是什么导致出现此错误?
UnitTest1.cs
using Microsoft.VisualStudio.TestTools.UnitTesting;
using ProductNamespace;
namespace TestProject2
{
[TestClass]
public class TestProduct
{
[TestMethod]
public void TestNewProduct()
{
Product mock_product = new Product(4.95);
Assert.IsInstanceOfType(mock_product, Product);
}
}
}
Product.cs
namespace ProductNamespace
{
public class Product
{
private double price;
public Product(double price)
{
this.price = price;
}
}
}
您似乎在尝试使用 IsInstanceOfType(object, Type)
method. To do that, you need to provide a Type
argument, but currently you've just specified the class name directly. That's not a valid C# expression - you need to use the typeof
operator 从 class 名称中获取 Type
:
Assert.IsInstanceOfType(mock_product, typeof(Product));
请注意,这确实不是一个有用的测试 - 您没有测试有关代码的任何内容,您实际上是在询问 .NET 是否正常运行。如果代码到达该行(即,如果构造函数没有抛出异常),那么它是 bound 通过 - 因为 new Xyz
的结果总是 Xyz
. (COM 接口有一些边缘情况,但与此处无关。)
Assert.IsInstanceOfType(mock_product, typeof(Product));
请尝试以上方法。根据official documentation,第二个参数应该是Type
.
熟悉 C# 后,在进行断言的行上进行单元测试时出现以下错误 Assert.IsInstanceTypeOf
。
Error CS0119 'Product' is a type, which is not valid in the given context
创建类型的事情已经完成。是什么导致出现此错误?
UnitTest1.cs
using Microsoft.VisualStudio.TestTools.UnitTesting;
using ProductNamespace;
namespace TestProject2
{
[TestClass]
public class TestProduct
{
[TestMethod]
public void TestNewProduct()
{
Product mock_product = new Product(4.95);
Assert.IsInstanceOfType(mock_product, Product);
}
}
}
Product.cs
namespace ProductNamespace
{
public class Product
{
private double price;
public Product(double price)
{
this.price = price;
}
}
}
您似乎在尝试使用 IsInstanceOfType(object, Type)
method. To do that, you need to provide a Type
argument, but currently you've just specified the class name directly. That's not a valid C# expression - you need to use the typeof
operator 从 class 名称中获取 Type
:
Assert.IsInstanceOfType(mock_product, typeof(Product));
请注意,这确实不是一个有用的测试 - 您没有测试有关代码的任何内容,您实际上是在询问 .NET 是否正常运行。如果代码到达该行(即,如果构造函数没有抛出异常),那么它是 bound 通过 - 因为 new Xyz
的结果总是 Xyz
. (COM 接口有一些边缘情况,但与此处无关。)
Assert.IsInstanceOfType(mock_product, typeof(Product));
请尝试以上方法。根据official documentation,第二个参数应该是Type
.