use*_*372 1 .net c# clr static class
我在C#中怀疑方法中的静态类使用.假设我们在另一个类中有一个带有两个参数int和Enum的方法.
public void DemoMethod(int pricePerTenant , TenantType tenantType){
//Method implementation
}
Run Code Online (Sandbox Code Playgroud)
如果我们实现静态类而不是Enum,C#不允许将静态类作为方法参数传递
public static class TenantType
{
public static readonly int TenantAdmin = 1;
public static readonly int TenantUser = 2;
public static readonly int PublicUser = 3;
}
//With static class parameters
public void DemoMethod(int pricePerTenant , TenantType tenantType){
//Method implementation
}
Run Code Online (Sandbox Code Playgroud)
为什么C#CLR拒绝将Static类作为参数?
谢谢
你永远不能实例化TenantType- 所以你唯一可能传入的价值DemoMethod就是null.考虑一下你如何调用这个方法 - 如果你打算打电话(比方说)DemoMethod(10, TenantType.TenantUser)那么那将是一个int争论,而不是TenantType反正.
基本上,静态类永远不会有实例,所以允许它们在您考虑实例的任何地方使用是没有意义的- 包括方法参数和类型参数.您应该感谢C#如此早地捕获您的错误,基本上 - 这是静态类的好处之一.
在这种情况下,它听起来真的应该有一个enum代替:
public enum TenantType
{
Admin = 1,
User = 2,
PublicUser = 3
}
Run Code Online (Sandbox Code Playgroud)
此时你可以接受它作为参数 - 你仍然可以调用DemoMethod(10, TenantType.User),但是以类型安全的方式,除非方法真的关心整数映射,否则它永远不会看到它.
| 归档时间: |
|
| 查看次数: |
147 次 |
| 最近记录: |