在Java中,有一個選項可以在可以使用的枚舉對象內寫入enum和函數。C中枚舉的方法#
在C#中是否存在這樣的可能性,還是僅僅是一個字符串集合,就是這樣嗎?
我試圖「覆蓋」ToString()
函數,它不編譯。有人有簡單的代碼示例嗎?
在Java中,有一個選項可以在可以使用的枚舉對象內寫入enum和函數。C中枚舉的方法#
在C#中是否存在這樣的可能性,還是僅僅是一個字符串集合,就是這樣嗎?
我試圖「覆蓋」ToString()
函數,它不編譯。有人有簡單的代碼示例嗎?
您可以編寫擴展方法,枚舉類型:
enum Stuff
{
Thing1,
Thing2
}
static class StuffMethods
{
public static String GetString(this Stuff s1)
{
switch (s1)
{
case Stuff.Thing1:
return "Yeah!";
case Stuff.Thing2:
return "Okay!";
default:
return "What?!";
}
}
}
class Program
{
static void Main(string[] args)
{
Stuff thing = Stuff.Thing1;
String str = thing.GetString();
}
}
沒有。你可以創建一個類,然後添加一堆屬性到類有點模仿枚舉,但那不是真的一樣的東西。
class MyClass
{
public string MyString1 { get{ return "one";} }
public string MyString2 { get{ return "two";} }
public string MyString3 { get{ return "three";} }
public void MyMethod()
{
// do something.
}
}
更好的模式是將你的方法放在與你的emum分開的類中。
這是我接受的答案。 – 2018-01-04 13:21:49
C#不容許枚舉,因爲它的使用方法不是基於類的原理,而是一個帶有字符串和值的二維數組。在這種情況下,Microsoft非常不鼓勵使用類,而是使用(data)struct(ures);而不是使用STRUCT旨在作爲數據及其處理程序的輕量級類,並且可以很好地處理函數。 C#及其編譯器不具備從JAVA獲知的跟蹤和效率功能,其中使用某個類/方法的次數越多,其運行速度越快,並且其使用變得「預期」。 C#根本沒有,所以區分,使用STRUCT而不是CLASS。
七票沒有一個單一的評論來解釋這個答案應該是錯誤的? C'mon guys ... – 2016-04-25 11:49:53
我想,200年後,人類終將成熟到足以理解這個人。但在那之前...抱歉,「-1」是我們唯一能做的事情。 – 2016-07-09 22:00:29
這篇文章中提供的所有信息都是錯誤的嗎? – 2016-08-09 13:20:10
另一種選擇是使用由創建的Enumeration Class Jimmy Bogard。
基本上,你必須創建一個繼承自他的Enumeration
的類。例如:
public class EmployeeType : Enumeration
{
public static readonly EmployeeType Manager
= new EmployeeType(0, "Manager");
public static readonly EmployeeType Servant
= new EmployeeType(1, "Servant");
public static readonly EmployeeType Assistant
= new EmployeeType(2, "Assistant to the Regional Manager");
private EmployeeType() { }
private EmployeeType(int value, string displayName) : base(value, displayName) { }
// Your method...
public override string ToString()
{
return $"{value} - {displayName}!";
}
}
然後你可以使用它像一個枚舉,與可能把方法裏面(中另一事物):
EmployeeType.Manager.ToString();
//0 - Manager
EmployeeType.Servant.ToString();
//1 - Servant
EmployeeType.Assistant.ToString();
//2 - Assistant to the Regional Manager
你可以用NuGet下載。
我不認爲你可以在C#中的Enum中使用方法。你想做什麼? – 2011-05-12 23:27:50
試圖獲取Java行爲並封裝Enums的關閉邏輯。無論如何,我從答案中看到這是不可能的 - 我會實施擴展。 – Eya 2011-05-13 09:00:00