![](/img/trans.png)
[英]In C#, can you use Reflection to find properties that don't have a getter?
[英]How to make an abstract getter in C# so you don't have to declare in every child?
我有一個抽象 class,它有一個實現抽象方法的方法,作為其子項中某個值的 getter 的占位符:
public abstract class MyAbstractClass {
public abstract int GetMyValue();
}
public class MyChildClass0 : MyAbstractClass {
int myValue = 1;
public override int GetMyValue {
return myValue;
}
}
public class MyChildClass1 : MyAbstractClass {
int myValue = 7;
public override int GetMyValue {
return myValue;
}
如您所見,吸氣劑在每個孩子身上的行為方式相同。 我的問題是是否有任何方法可以使該 getter 成為非抽象方法,所以我只需要在抽象 class 中實現一次。每次我想訪問任何子 class 中的 myValue 時,我只需調用 GetMyValue 方法即可它繼承自 MyAbstractClass。
我不知道該怎么做,因為我不知道如何讓 getter 訪問該字段,因為它沒有在摘要 class 中聲明,而是在子項中聲明。
屬性和默認構造函數在這里非常有用。
這會強制所有派生類向MyAbstractClass
提供值。
public abstract class MyAbstractClass {
protected MyAbstractClass(int myValue)
{
MyValue = myValue;
}
public int MyValue { get; }
}
在您的特定情況下,您需要一個與實現 class 緊密耦合的 int,但只公開公開,但如果有人忘記在MyValue
上設置 MyValue,並且該值指定為,您可能還需要編譯時錯誤,而不是運行時錯誤Class 級別,而不是構造函數級別(創建 class 實例的東西不能設置/修改類MyValue
,它是類固有的)
以下將起作用:
public abstract class MyAbstractClass {
public abstract int MyValue { get; }
}
public class MyChildClass0 : MyAbstractClass {
// C#6 I believe added this handy shorthand for Getter Properties
public override int MyValue => 1;
}
public class MyChildClass1 : MyAbstractClass {
// This is the same as above
public override int MyValue {
get => 7;
}
}
編譯器會糾纏你並要求在編譯之前在你的實現具體MyValue
上實現 MyValue,這是理想的,因為這會強制設置它。
由於GetMyValue
將始終返回myValue
為什么不能將myValue
移動到抽象 class 中?
像這樣:
public abstract class MyAbstractClass {
int myValue;
public int GetMyValue() {
return myValue;
}
// If you want to change myValue you could also create a setter
public int SetMyValue(int myValue) {
this.myValue = myValue;
}
}
public class MyChildClass0 : MyAbstractClass {
public MyChildClass() {
// In constructor you can call a setter to update your value
SetMyValue(1);
// Or you could mark myValue as a protected field so
// that MyAbstractClass children had access to it.
// Then you could just directly assign a value to it
}
}
public class MyChildClass1 : MyAbstractClass {
public MyChildClass1() {
SetMyValue(7);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.