这个多余的只读前缀
This redundant Readonly prefix
internal abstract class ReadonlyCoefs
{
public const Boolean Allowed = true;
public const Boolean Disallowed = false;
public abstract Boolean GetCoef();
}
internal class Coefs : ReadonlyCoefs
{
public override Boolean GetCoef() { ... }
public void SetCoef() { ... }
}
现在,假设我想在这样的地方使用它
if (variable == ReadonlyCoefs.Allowed)
...
我不希望有 Readonly 前缀。
在这种情况下,我可以只添加实例方法 IsAllowed 和 SetAllowed,SetDisallowed,但是如果有很多常量,这种情况怎么办?
不,没有办法做你想做的事,至少现在是这样。在 C# 6 中,可以使用 using
指令导入 class 的静态成员:
using static SomeNamespace.ReadonlyCoefs;
这将允许在不指定类型名称的情况下访问 ReadonlyCoefs
的静态成员。
就是说,鉴于您当前的设计,我同意 Hans 的观点,您应该使用 enum
:
enum CoefPermission
{
Allowed,
Disallowed,
}
internal abstract class ReadonlyCoefs
{
public abstract CoefPermission GetCoef();
}
然后:
if (variable == CoefPermission.Allowed) ...
这也应该与 C# 6 中的 using static
功能兼容。即你可以有 using static SomeNamespace.CoefPermission;
然后代码可以读取 if (variable == Allowed) ...
.
现在,所有 都说,我对您当前的设计持怀疑态度。也许它对非 bool
值有意义(特别是如果您切换到基于 enum
的方法)。但是你没有表现出那样的东西。您所拥有的只是 bool
值,恕我直言,为这些值制作常量 或 枚举是很愚蠢的。相反,为什么不只是有这样的东西:
internal abstract class ReadonlyCoefs
{
public abstract Boolean IsCoefAllowed();
}
internal class Coefs : ReadonlyCoefs
{
public override Boolean IsCoefAllowed() { ... }
public void SetIsCoefAllowed() { ... }
}
然后:
if (variable) ...
如果你给变量起个好名字就更好了:
if (isCoefAllowed) ...
恕我直言,这更具可读性和可维护性。
internal abstract class ReadonlyCoefs
{
public const Boolean Allowed = true;
public const Boolean Disallowed = false;
public abstract Boolean GetCoef();
}
internal class Coefs : ReadonlyCoefs
{
public override Boolean GetCoef() { ... }
public void SetCoef() { ... }
}
现在,假设我想在这样的地方使用它
if (variable == ReadonlyCoefs.Allowed)
...
我不希望有 Readonly 前缀。
在这种情况下,我可以只添加实例方法 IsAllowed 和 SetAllowed,SetDisallowed,但是如果有很多常量,这种情况怎么办?
不,没有办法做你想做的事,至少现在是这样。在 C# 6 中,可以使用 using
指令导入 class 的静态成员:
using static SomeNamespace.ReadonlyCoefs;
这将允许在不指定类型名称的情况下访问 ReadonlyCoefs
的静态成员。
就是说,鉴于您当前的设计,我同意 Hans 的观点,您应该使用 enum
:
enum CoefPermission
{
Allowed,
Disallowed,
}
internal abstract class ReadonlyCoefs
{
public abstract CoefPermission GetCoef();
}
然后:
if (variable == CoefPermission.Allowed) ...
这也应该与 C# 6 中的 using static
功能兼容。即你可以有 using static SomeNamespace.CoefPermission;
然后代码可以读取 if (variable == Allowed) ...
.
现在,所有 都说,我对您当前的设计持怀疑态度。也许它对非 bool
值有意义(特别是如果您切换到基于 enum
的方法)。但是你没有表现出那样的东西。您所拥有的只是 bool
值,恕我直言,为这些值制作常量 或 枚举是很愚蠢的。相反,为什么不只是有这样的东西:
internal abstract class ReadonlyCoefs
{
public abstract Boolean IsCoefAllowed();
}
internal class Coefs : ReadonlyCoefs
{
public override Boolean IsCoefAllowed() { ... }
public void SetIsCoefAllowed() { ... }
}
然后:
if (variable) ...
如果你给变量起个好名字就更好了:
if (isCoefAllowed) ...
恕我直言,这更具可读性和可维护性。