簡體   English   中英

C#方法中的靜態參數

[英]Static parameters in C# methods

我在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) ,但是以類型安全的方式進行,除非該方法真正關心整數映射,否則它永遠DemoMethod(10, TenantType.User)看見。

因為如果您將TenantType tenantType指定為參數,則會告訴C#,您在此處需要TenantType實例 而且由於您未通過一項,因此無法使用。

反過來,這將:

public void DemoMethod(int pricePerTenant, int tenantType) {

}

DemoMethod(3, TenantType.TenantAdmin);

但是 有一種類似於您的方法,該方法實際上可以工作:

public class TenantType {

    private int value;

    private TenantType(int newValue)
    {
        value = newValue;
    }

    public override bool Equals(object obj)
    {
        return (obj is TenantType && (obj as TenantType).value == this.value;
    }

    public override int GetHashCode()
    {
        return value;
    }

    public static bool operator == (TenantType left, TenantType right)
    {
        return left.Equals(right);
    }

    public static bool operator != (TenantType left, TenantType right)
    {
        return !(left.Equals(right));
    }

    public static TenantType Admin = new TenantType(1);
    public static TenantType User = new TenantType(2);
    public static TenantType PublicUser = new TenantType(3);
}

public void DemoMethod(int pricePerTenant, TenantType tenantType)
{

}

DemoMethod(4, TenantType.Admin);

如您所見,這比使用枚舉的最簡單解決方案需要更多的工作(畢竟,這正是它們創建的目的)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM