我正在尝试检索某种类型的属性。例如在Player类中:
public Player(string name, Stat endurance, Stat sprint, Stat dribble, Stat passing, Stat shooting)
{
//Some code
}
public Stat Endurance { get; private set; }
public Stat Sprint { get; private set; }
public Stat Dribble { get; private set; }
public Stat Passing { get; set; }
public Stat Shooting { get; private set; }
public double OverallSkillLevel { get; private set; } {
public string Name { get; private set; }
public void CalculateAverage()
{
double sumOfStat = this.Endurance.Level + this.Sprint.Level +
this.Dribble.Level + this.Shooting.Level +
this.Passing.Level;
//MethodOne:
Type type = this.GetType();
int countOne = type .GetProperties().Count(x => x.MemberType is Stat);
//MethodTwo
double countTwo = this.GetType().GetFields().Count(x => x is Stat);
//this.OverallSkillLevel = Math.Round((sumOfStat / ), 0);
}
我希望变量“ countOne”或“ countTwo”仅将Stat属性返回给我。但我总是得到0
答案 0 :(得分:0)
您正在检查PropertyInfo
对象的错误属性;关于msdn的MemberInfo.MemberType
属性:
在派生类中重写时,获取一个MemberTypes值,该值指示成员的类型-方法,构造函数,事件等。
您应该检查PropertyInfo.PropertyType
属性。同样,在这种情况下,使用is
关键字进行的检查在比较Type
实例时使用Type.IsAssignableFrom()
或==
是错误的。
这应该可以解决问题:
//MethodOne:
int countOne = this.GetType().GetProperties().Count(x => x.PropertyType == typeof(Stat));