【发布时间】:2020-06-19 22:00:45
【问题描述】:
所以首先我有实现某些东西的通用类。
public class MyGenericClass<T> where T : class
{
...
public T SomeFunction(T t) {...}
...
}
然后我想要这个泛型类的两个“实例”(具有不同的类型),可以在我的项目中的任何地方使用,但不知道该怎么做。
使用全局可能是一种选择,但我想创建另一个包含不同泛型类的静态类。
public static class CosmosDBHelper
{
public static MyGenericClass<T1> t1;
public static MyGenericClass<T2> t2;
}
但是 StyleCop 会报错 SA1401 "Field should be private"。我找到了以下解决方案,但它看起来很多余。
public static class CosmosDBHelper
{
private static MyGenericClass<T1> t1;
public static MyGenericClass<T1> T1 { get { return t1; } }
private static MyGenericClass<T2> t2;
public static MyGenericClass<T2> T2 { get { return t2; } }
}
有没有更好的办法?
谢谢,
【问题讨论】:
-
可以使用静态构造函数
-
通常只公开属性,不公开字段。您应该能够简化为
public static MyGenericClass<T1> T1 { get; }和T2。 -
SA1401 并非特定于泛型类。您能否请edit 提问以澄清为什么您认为这里有一些特定于泛型的东西?此外,“不喜欢它”并不是真正可以在 SO 上回答的问题 - 显示您想要修复的代码的问题到底是什么? (您可能还想阅读csharpindepth.com/Articles/Singleton,因为您似乎试图实现单例行为)
标签: c# static generic-programming