gpt4 book ai didi

c# - C#方法中的静态参数

转载 作者:太空宇宙 更新时间:2023-11-03 17:31:12 25 4
gpt4 key购买 nike

我在C#中对方法中的静态类用法有疑问。假设我们在另一个类中有一个带有两个参数int和Enum的方法。

public void DemoMethod(int pricePerTenant , TenantType tenantType){
//Method implementation
}


如果我们实现一个静态类而不是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
}


为什么C#CLR拒绝采用静态类作为参数?

谢谢

最佳答案

您永远无法实例化TenantType-因此,可能传递给DemoMethod的唯一值将是null。考虑一下您将如何调用该方法-如果您希望调用(例如)DemoMethod(10, TenantType.TenantUser),那么那将是int参数而不是TenantType

基本上,静态类永远不会有实例,因此不允许将它们用于您要考虑实例的任何地方(包括方法参数和类型参数)是没有意义的。您应该很感激C#这么早就捕获错误,基本上-这是静态类的好处之一。

在这种情况下,听起来确实应该有一个枚举:

public enum TenantType
{
Admin = 1,
User = 2,
PublicUser = 3
}


到那时,您可以接受它作为参数-您仍然可以调用 DemoMethod(10, TenantType.User),但是以一种类型安全的方式,除非该方法真正关心整数映射,否则就永远不必看到它。

关于c# - C#方法中的静态参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22960032/

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