C# 空构造函数中两个的类耦合(VStudio代码分析)
Visual studio代码分析报告此构造函数的两个类耦合:C# 空构造函数中两个的类耦合(VStudio代码分析),c#,visual-studio,code-analysis,C#,Visual Studio,Code Analysis,Visual studio代码分析报告此构造函数的两个类耦合: protected AcceptInvitation() { } public AcceptInvitation(int accountId, string invitationKey) { if (string.IsNullOrEmpty(invitationKey)) throw new ArgumentNullException("invitationKey"); if (accountId <= 0)
protected AcceptInvitation()
{
}
public AcceptInvitation(int accountId, string invitationKey)
{
if (string.IsNullOrEmpty(invitationKey)) throw new ArgumentNullException("invitationKey");
if (accountId <= 0) throw new ArgumentOutOfRangeException("accountId");
AccountId = accountId;
InvitationKey = invitationKey;
}
有人能解释一下原因吗?首先,我认为这是因为其他类依赖它。但我使用了“查找所有用法”,没有报告任何用法
那么,我如何才能理解为什么VisualStudio会为此报告“2”
然后我得到了另一个构造函数:
protected AcceptInvitation()
{
}
public AcceptInvitation(int accountId, string invitationKey)
{
if (string.IsNullOrEmpty(invitationKey)) throw new ArgumentNullException("invitationKey");
if (accountId <= 0) throw new ArgumentOutOfRangeException("accountId");
AccountId = accountId;
InvitationKey = invitationKey;
}
在没有看到整个类的代码的情况下,我假设您有两个内联初始化的类字段。例如:
class Class1
{
private Person = new Person();
private Automobile = new Automobile();
protected Class1() { }
}
上面的类将显示受保护构造函数的类耦合为2,因为运行构造函数将导致这两个字段初始化
在看到整个类之后,很明显,耦合是由请求的继承引起的 为受保护构造函数生成的IL如下所示:
.method family hidebysig specialname rtspecialname instance void .ctor () cil managed
{
IL_0000: ldarg.0
IL_0001: call instance void class YourNamespace.Request`1<class YourNamespace.AcceptInvitationReply>::.ctor()
IL_0006: nop
IL_0007: nop
IL_0008: ret
}
.methodfamily hidebysing specialname rtspecialname实例void.ctor()cil托管
{
IL_0000:ldarg.0
IL_0001:调用实例void类YourNamespace.Request`1::.ctor()
IL_0006:没有
IL_0007:没有
IL_0008:ret
}
如您所见,构造函数肯定与这两个类耦合。在这两个构造函数中都有一个隐式的
base()
这将创建一个与基类的耦合,因为它是泛型的,所以您将看到另外两个耦合;基类及其泛型类型参数。如果它不是通用的,您只会有一个额外的耦合。很好的一点,不幸的是,这不是我的情况。我添加了您的类从请求继承的整个类。这意味着您的构造函数必须调用请求类上的构造函数(即使未定义该构造函数)。为了进行该调用,构造函数必须同时知道Request类和AcceptInvitationReply类.基类及其泛型类型参数。在两个构造函数中都有一个隐式的
base()