2011-11-08 52 views
4

下面的代碼似乎是不可能編譯的,不管我試圖施展它有多難:P可以somone請告訴我我做錯了什麼?爲什麼不能通過表達式引用類型?

public class LUOverVoltage 
{ 
    public string Name { get; set; } 
    public enum OVType { OVLH, OVLL } 

    public List<string> PinGroups = new List<string>(); 

    public void Add(string name, OVType type, string Grp) 
    { 
     this.Name = name; 
     this.OVType = type; //Why cannot reference a type through an expression? 

     PinGroups.Add(Grp); 
    } 
} 
+0

你會得到什麼樣的編譯錯誤? – Connell

+0

「OVType」:不能通過表達式引用類型; –

回答

13

你混淆了enum類型的字段與枚舉類型本身。您的代碼與說string="bla"一樣有用。

public enum OVType { OVLH, OVLL } 
public class LUOverVoltage 
{ 
    public string Name { get; set; } 
    public OVType OVType { get; set; } 

聲明一個名爲OVType類型和具有相同名稱的屬性。現在你的代碼應該工作。


作爲一個側面說明,無論你的類型名稱和屬性名稱違反.NET命名準則。

我會列舉枚舉類型OverVoltKind和屬性Kind

0

OVType是變量的類型。您已將其設置爲enum,這是用於聲明新枚舉類型的關鍵字。您需要將OVType聲明爲枚舉類型,然後將其用作屬性類型。

public enum OVType { OVLH, OVLL } 

public class LUOverVoltage 
{ 
    public string Name { get; set; } 
    public OVType OVType { get; set; } 

    public List<string> PinGroups = new List<string>(); 

    public void Add(string name, OVType type, string Grp) 
    { 
     this.Name = name; 
     this.OVType = type; 

     PinGroups.Add(Grp); 
    } 
} 
+0

對不起,但這並沒有讓它更好。 –

+0

public OVType OVType {OVLH,OVLL}不會編譯 – MattDavey

+0

啊!好像我錯過了那樣。現在更新。 – Connell

4

您沒有設置屬性,而是嘗試設置枚舉。

添加一個public OVType ovType並使用this.ovType = type

public class LUOverVoltage 
{ 
    public enum OVType { OVLH, OVLL } 

    public string Name { get; set; } 
    public OVType ovType; 
    public List<string> PinGroups = new List<string>(); 

    public void Add(string name, OVType type, string Grp) 
    { 
     this.Name = name; 
     this.ovType = type; 

     PinGroups.Add(Grp); 
    } 
} 
1

OVType - 不是一個領域,其類型

試試這個

public class LUOverVoltage 
{ 
    public string Name { get; set; } 
    public OVType Type {get; set;} 

    public enum OVType { OVLH, OVLL } 

    public List<string> PinGroups = new List<string>(); 

    public void Add(string name, OVType type, string Grp) 
    { 
     this.Name = name; 
     this.Type = type; 

     PinGroups.Add(Grp); 
    } 
} 
2

您已經定義的類內的Enum。你沒有做的是聲明一個變量來保存該枚舉的一個實例。

public enum OVType { OVLH, OVLL } 

public class LUOverVoltage 
{ 
    public string Name { get; set; } 
    public OVType OVType { get; set; } 

    public List<string> PinGroups = new List<string>(); 

    public void Add(string name, OVType type, string Grp) 
    { 
     this.Name = name; 
     this.OVType = type; // setting the property, not the enum definition 

     PinGroups.Add(Grp); 
    } 
} 
相關問題