如何继承class int成员?
How to get inheriting class int members?
我有这样一个基础class:
public class Marker {
public int[] GetChildMarks() {
//Somehow Get Child int members
}
public int ShallNotBeInArray;
}
public class MyMarker : Marker {
public int Size, Number;
}
public class TedsMarker : Marker {
public int Power;
}
//... somewhere in main
var m = new MyMarker(){Size=3, Number = 666};
var arr = m.GetChildMarks(); // [Size, Number, Any other ints in MyMarker ]
var t = new TedsMarker() {Power=999};
var arr2 = t.GetChildMarks(); // [Power, Any other ints in TedsMarker]
那么有可能吗?如何使用反射在 C# 中做这样的事情?
可以这样实现:
public class Marker
{
public int[] GetChildMarks()
{
return new int[]
{
(int)GetType().GetField("Size").GetValue(this),
(int)GetType().GetField("Number").GetValue(this)
};
}
public int ShallNotBeInArray;
}
这假设 child class 有这两个字段并且它们是 int
类型。
由于没有强制执行(实际上不可能,因为这些是字段,而不是属性),这种方法很适合产生运行时错误。
编辑:
可以像这样检索所有字段的值:
public class Marker
{
public int[] GetChildMarks()
{
List<int> allIntegerFields = new List<int>();
// DeclaredOnly: only get fields declared by this type, not the ones declared by base classes
// Public | Instance: Only get non-static, public fields
foreach(FieldInfo fieldInfo in GetType().GetFields(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance))
{
if(fieldInfo.FieldType == typeof(int))
{
allIntegerFields.Add((int)fieldInfo.GetValue(this));
}
}
return allIntegerFields.ToArray();
}
public int ShallNotBeInArray;
}
我有这样一个基础class:
public class Marker {
public int[] GetChildMarks() {
//Somehow Get Child int members
}
public int ShallNotBeInArray;
}
public class MyMarker : Marker {
public int Size, Number;
}
public class TedsMarker : Marker {
public int Power;
}
//... somewhere in main
var m = new MyMarker(){Size=3, Number = 666};
var arr = m.GetChildMarks(); // [Size, Number, Any other ints in MyMarker ]
var t = new TedsMarker() {Power=999};
var arr2 = t.GetChildMarks(); // [Power, Any other ints in TedsMarker]
那么有可能吗?如何使用反射在 C# 中做这样的事情?
可以这样实现:
public class Marker
{
public int[] GetChildMarks()
{
return new int[]
{
(int)GetType().GetField("Size").GetValue(this),
(int)GetType().GetField("Number").GetValue(this)
};
}
public int ShallNotBeInArray;
}
这假设 child class 有这两个字段并且它们是 int
类型。
由于没有强制执行(实际上不可能,因为这些是字段,而不是属性),这种方法很适合产生运行时错误。
编辑:
可以像这样检索所有字段的值:
public class Marker
{
public int[] GetChildMarks()
{
List<int> allIntegerFields = new List<int>();
// DeclaredOnly: only get fields declared by this type, not the ones declared by base classes
// Public | Instance: Only get non-static, public fields
foreach(FieldInfo fieldInfo in GetType().GetFields(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance))
{
if(fieldInfo.FieldType == typeof(int))
{
allIntegerFields.Add((int)fieldInfo.GetValue(this));
}
}
return allIntegerFields.ToArray();
}
public int ShallNotBeInArray;
}