![](/img/trans.png)
[英]C# - How to populate a custom class array containing integer primitives?
[英]Custom primitives in C#?
除了這個問題的可疑性之外,我想問一下是否有可能沿着這些方向做點什么。
class MyPrimitive {
String value;
public String Value {
get { return value; }
set { this.value = value; }
}
}
// Instead of doing this...
MyPrimitive a = new MyPrimitive();
a.Value = "test";
String b = a.Value;
// Isn't there a way to do something like this?
MyPrimitive a = "test";
String b = a;
我喜歡使用屬性將原始類型包裝到自定義類中,以使get
和set
方法執行其他操作,例如驗證。
因為我經常這樣做,所以我認為有一個更簡單的語法,比如標准基元,這樣會很好。
盡管如此,我懷疑這不僅不可行,而且在概念上也可能是錯誤的。 任何見解都會受到歡迎,謝謝。
使用值類型( struct
)並從賦值右側所需的類型中為其提供隱式轉換運算符 。
struct MyPrimitive
{
private readonly string value;
public MyPrimitive(string value)
{
this.value = value;
}
public string Value { get { return value; } }
public static implicit operator MyPrimitive(string s)
{
return new MyPrimitive(s);
}
public static implicit operator string(MyPrimitive p)
{
return p.Value;
}
}
編輯:使結構不可變,因為馬克格拉維爾是絕對正確的。
你可以使用隱式轉換 。 不建議這樣做,但是:
public static implicit operator string(MyString a) {
return a.Value;
}
public static implicit operator MyString(string a) {
return new MyString { value = a; }
}
再次,糟糕的做法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.