Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C#泛型铸造_C#_.net_Generics - Fatal编程技术网

C#泛型铸造

C#泛型铸造,c#,.net,generics,C#,.net,Generics,VisualStudio2008能够自动创建单元测试存根。我用它创建了一些基本的单元测试,但我被一些东西弄糊涂了: private class bla : BaseStoreItem { // } /// <summary> ///A test for StoreData ///</summary> public void StoreDataTestHelper<T>() where T : BaseStor

VisualStudio2008能够自动创建单元测试存根。我用它创建了一些基本的单元测试,但我被一些东西弄糊涂了:

  private class bla : BaseStoreItem
     {
     //
     }

  /// <summary>
  ///A test for StoreData
  ///</summary>
  public void StoreDataTestHelper<T>() where T : BaseStoreItem
     {
     FileStore<T> target = new FileStore<T>(); // TODO: Initialize to an appropriate value

     BaseStoreItem data = new bla();

     target.StoreData(data);
     }

  [TestMethod()]
  public void StoreDataTest()
     {
     //Assert.Inconclusive("No appropriate type parameter is found to satisfies the type constraint(s) of T. " +
     //        "Please call StoreDataTestHelper<T>() with appropriate type parameters.");

     StoreDataTestHelper<bla>();
     }
私有类bla:BaseStoreItem
{
//
}
/// 
///存储数据的测试
///
public void StoreDataTestHelper(),其中T:BaseStoreItem
{
FileStore target=new FileStore();//TODO:初始化为适当的值
BaseStoreItem数据=新bla();
目标。存储数据(数据);
}
[TestMethod()]
public void StoreDataTest()
{
//Assert.Inconclusive(“未找到满足T的类型约束的适当类型参数。”+
//“请使用适当的类型参数调用StoreDataTestHelper()”);
StoreDataTestHelper();
}
为什么当T的类型为“bla”时会出现“错误:无法将类型“StorageUnitTests.FileStoreTest.bla”转换为“T”

我知道“bla”不是一个好的函数名,但它只是一个例子。

为什么不这样? (如果您有权访问t,那么在StoreDataTestHelper中创建bla实例没有多大意义)

public void StoreDataTestHelper(),其中T:BaseStoreItem,new()
{
FileStore target=newfilestore();
T数据=新的T();
目标。存储数据(数据);
}

因为,如果
T
DerivedStoreItem
(继承
BaseStoreItem
),则通过存储
BaseStoreItem

,将违反
文件存储的类型,这是有意义的。通过指定
T:BaseStoreItem
,您已经保证了
T
将是一种将
BaseStoreItem
作为基类的类型,而不一定是
BaseStoreItem
。因此,如果T后来被设置为从
BaseStoreItem
派生的某个类型,那么您的
target.StoreData(data)行将执行非法操作

虽然在您的情况下,只在
T
设置为
bla
时调用
StoreDataTestHelper
,但C#的类型检查器需要确保
StoreDataTestHelper
的代码通常是类型安全的。这是强类型语言的一个好处:它能在你犯错误之前捕捉到潜在的输入错误

当T为“bla”类型时

您的上述条件仅适用于当前情况,但我可以创建另一个类

public class Bla2: BaseStoreItem {...
然后什么的,Bla2都不是从bla派生的,所以如果我尝试使用

StoreDataTestHelper<Bla2>(); 
StoreDataTestHelper();

这是错误的,编译器足够聪明,能够理解在这种情况下它不会工作,计算机语言不像英语,它们被创造出来在所有条件下都能工作。它们的设计使语言规则在任何情况下都是正确的。如果它们不同,您将无法找到错误所在。

@Akash为什么?Activator.CreateInstance使用反射,速度很慢。它认为新的T()更优雅。gsharp,对不起,我错过了代码中的new()约束,在问题中,new()没有被指定,我从来不知道“new()”位。谢谢你,格沙普:)
StoreDataTestHelper<Bla2>();