gpt4 book ai didi

c# - 如何修复 CA1000 不要在泛型类型上声明静态成员

转载 作者:行者123 更新时间:2023-12-04 01:50:17 26 4
gpt4 key购买 nike

我正在使用 Microsoft.CodeAnalysis.FxCopAnalyzersCA1000规则如下。

Do not declare static members on generic types.



如何修复违规行为

To fix a violation of this rule, remove the static member or change it to an instance member.



何时禁止警告:

Do not suppress a warning from this rule. Providing generics in a syntax that is easy to understand and use reduces the time that is required to learn and increases the adoption rate of new libraries.



我的代码如下。 Success方法是触发规则的方法。
public class ResultResponse
{
internal ResultResponse(bool isSuccess)
{
IsSuccess = isSuccess;
}

public bool IsSuccess { get; }

public static ResultResponse Failed()
=> new ResultResponse(false);
}

public class ResultResponse<T> : ResultResponse
{
internal ResultResponse(T value, bool isSuccess)
: base(isSuccess)
{
Value = value;
}

public T Value { get; }

public static ResultResponse<T> Success(T value)
=> new ResultResponse<T>(value, true);
}

我可以公开构造函数并在上面的示例中使用它,但我也有这样的情况,我想将构造函数保留在内部以确保正确使用类型。

正在搬家 Success非泛型类型的正确方法?
public class ResultResponse
{
internal ResultResponse(bool isSuccess)
{
IsSuccess = isSuccess;
}

public bool IsSuccess { get; }

public static ResultResponse Failed()
=> new ResultResponse(false);

public static ResultResponse<T> Success<T>(T value)
=> new ResultResponse<T>(value, true);
}

public class ResultResponse<T> : ResultResponse
{
internal ResultResponse(T value, bool isSuccess)
: base(isSuccess)
{
Value = value;
}

public T Value { get; }
}

最佳答案

Is moving the Success method to the non generic type the correct aproach?



这是一个体面的方法。请注意,现在,您可以调用:
ResultResponse.Success(someat);

并且编译器将从 someat 推断泛型类型.在您之前的代码中,因为您正在调用 static方法,你总是不得不(“冗余”)指定类型参数:
ResultResponse<int>.Success(someat);

关于c# - 如何修复 CA1000 不要在泛型类型上声明静态成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53449435/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com