仅获取继承类的父字段
我有一个名为 Stats 的类
public class Stats : ScriptableObject
{
public double vitality;
public double stamina;
public double endurance;
}
我还有一个继承 Stats 的类
public class Equipment : Stats
{
public string name;
// other fields that define equipment
}
我希望能够从继承自 Equipment 的 Stats 实例中获取所有字段
所以我将其添加到 Interface 类中
public void AddStats(Equipment equippedItem)
{
Stats stats = equippedItem as Stats;
if (stats != null)
{
GetPropertyValues(stats);
}
}
public static void GetPropertyValues(System.Object obj)
{
Type t = obj.GetType();
FieldInfo[] fis = t.GetFields(BindingFlags.Instance | BindingFlags.Public);
foreach (var fieldInfo in fis)
Debug.Log(fieldInfo.FieldType + " " + fieldInfo.Name + " " + fieldInfo.GetValue(obj));
}
问题是它正在获取所有字段以及设备中的字段。
我怎样才能做到只从统计数据中获取字段?
I have a class called Stats
public class Stats : ScriptableObject
{
public double vitality;
public double stamina;
public double endurance;
}
I also have a class that inherits Stats
public class Equipment : Stats
{
public string name;
// other fields that define equipment
}
I want to be able to get all the fields from the instance of Stats that is inherited from Equipment
So I added this in an Interface class
public void AddStats(Equipment equippedItem)
{
Stats stats = equippedItem as Stats;
if (stats != null)
{
GetPropertyValues(stats);
}
}
public static void GetPropertyValues(System.Object obj)
{
Type t = obj.GetType();
FieldInfo[] fis = t.GetFields(BindingFlags.Instance | BindingFlags.Public);
foreach (var fieldInfo in fis)
Debug.Log(fieldInfo.FieldType + " " + fieldInfo.Name + " " + fieldInfo.GetValue(obj));
}
The issue is that it is getting all the fields from the Equipment as well.
How could I make it so that only gets the fields from Stats?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不要使用
但传入您的目标类型
您可以对此用例进行重载,
并添加检查给定的
obj
是否为type
类型或子类或与泛型相同
,
反射永远不会“美丽”;)
Don't use
but pass in your target type
You could have an overload for this use case and have e.g.
and add a check if the given
obj
is of typetype
or a subclassOr the same as a generic
and
Reflection is never going to be "beautiful" ;)
我在这里找到了一个解决方案 如何在 C# 中使用反射获取自定义方法列表
所以我创建了一个名为 stat 的属性
,并将此属性添加到我想要在 Stats 类中获取的所有变量:
然后我更新了
GetPropertyValues
方法来获取属性并将其添加到数组中。I have found a solution here How to get custom a list of methods with reflection in C#
so I created a attribute called stat
And I added this attribute to all the variables I wanted to get in my Stats class:
Then I updated my
GetPropertyValues
method to pick up the attributes and added it to an array.