سؤال
وبصرف النظر عن مشكوك فيها فائدة هذا, أود أن أسأل ما إذا كان من الممكن أن تفعل شيء على طول هذه الخطوط.
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;
}
}
وتحرير: مصنوعة من غير قابل للتغيير البنية لمارك Gravell على حق تماما
نصائح أخرى
هل يمكن استخدام ضمني الصب.ليس من المستحسن ، ولكن:
public static implicit operator string(MyString a) {
return a.Value;
}
public static implicit operator MyString(string a) {
return new MyString { value = a; }
}
مرة أخرى, الممارسة السيئة.
لا تنتمي إلى StackOverflow