繁体   English   中英

使用foreach语句操纵类的成员

[英]manipulating members of a class using foreach statement

我的课有一堆可为null的double属性。 在运行时,其中一些具有0值,我将在发送操作之前将它们设置为null。 我知道我们可以使用foreach语句来遍历放置在类中的集合 ,因此我希望对此问题使用相同的技术。 正如我在这种情况下所说的,我不使用集合,因此实现IEnumerable是一种毫无意义的想法。 有什么办法可以在全班同学之间移动吗?

我已经试过了

Class1 c=new Class1(){Age = 12,Family = "JR",Name = "MAX"};
foreach (string member in c)
{
    Console.WriteLine(member);
}
Console.ReadKey();

实施IEnumerable

public IEnumerator GetEnumerator()
{
    // ?!
}

您必须使用反射,请看

如何获取类的属性列表?

我加了新的双打? 课堂上的财产。

    class Class1
    {
        public int Age { get; set; }
        public string Family { get; set; }
        public string Name { get; set; }

        public double? d { get; set; }
    }

    [Test]
    public void MyTest()
    {
            Class1 c = new Class1() { Age = 12, Family = "JR", Name = "MAX" };
            foreach (var prop in c.GetType().GetProperties().Where(x => x.PropertyType == typeof(double?)))
            {
                Console.WriteLine("{0}={1}", prop.Name, prop.GetValue(c));
                prop.SetValue(c, (double?)null); // set null as you wanted
            }
    }

您可以为此使用ReflectionLinq

using System.Reflection;
...

private static void ApplyNullsForZeroes(Object value) {
  if (null == value)
    return; // Or throw exception 

  var props = value.GetType()
    .GetProperties(BindingFlags.Public | BindingFlags.Instance)
    .Where(p => p.CanRead && p.CanWrite)
    .Where(p => p.PropertyType == typeof(Nullable<Double>));

  foreach (var p in props)
    if (Object.Equals(p.GetValue(value), 0.0))
      p.SetValue(value, null);
}

测试

public class MyClass {
  public MyClass() {
    Value = 0.0;
  }

  public Double? Value {
    get;
    set;
  }
}

...

MyClass test = new MyClass();

ApplyNullsForZeroes(test);

if (test.Value == null)
  Console.Write("It's null now");

正如您所说的,您具有属性,那么为什么不将它们用作Property呢?

get使用条件。 获取属性值时返回null

get
{
    return Age == 0 ? null : Age; //supposing "Age" is double in case to show an example
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM