【问题标题】:Got SA1401 in static class definition [duplicate]在静态类定义中得到 SA1401 [重复]
【发布时间】: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&lt;T1&gt; T1 { get; } 和 T2。
  • SA1401 并非特定于泛型类。您能否请edit 提问以澄清为什么您认为这里有一些特定于泛型的东西?此外,“不喜欢它”并不是真正可以在 SO 上回答的问题 - 显示您想要修复的代码的问题到底是什么? (您可能还想阅读csharpindepth.com/Articles/Singleton,因为您似乎试图实现单例行为)

标签: c# static generic-programming


【解决方案1】:

这与在静态类中使用泛型类无关。规则SA1401 只是声明类字段不应该是公共的。

阅读文档,我们发现“每当类中的字段被授予非私有访问权限时,就会违反此规则。出于可维护性的原因,应始终将属性用作将字段暴露在外部的机制一个类,并且字段应始终声明为具有私有访问权限。这允许属性的内部实现随时间变化而无需更改类的接口。"

有两种解决方案:

  1. 将字段设为私有:
    private static MyGenericClass&lt;T1&gt; t1;
    private static MyGenericClass&lt;T2&gt; t2;
  2. 将字段更改为属性:
    public static MyGenericClass&lt;T1&gt; t1 { get; } // Add a set to make it writeable
    public static MyGenericClass&lt;T2&gt; t2 { get; }

或者,如果需要,将两者结合起来(其中私有字段是公共属性的支持字段,正如您在解决方案中所使用的那样)。

另外,为了清楚起见,传递给MyGenericClass 的类型必须在基于它们创建字段或属性时定义。属性t1 和t2 应该是特定的、不同的类型,并且应该这样声明:

public static MyGenericClass<SomeClass> MyCustomClassInstance { get; }
public static MyGenericClass<string> MyStringClassInstance { get; }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-08-17
    • 1970-01-01
    • 1970-01-01
    • 2018-06-09
    • 2011-04-21
    • 2016-01-28
    • 1970-01-01
    相关资源
    最近更新 更多