简体   繁体   English

使用foreach语句操纵类的成员

[英]manipulating members of a class using foreach statement

My class has a bunch of nullable double properties. 我的课有一堆可为null的double属性。 At run time some of them have 0 value and i am going to set them null before sending action. 在运行时,其中一些具有0值,我将在发送操作之前将它们设置为null。 I know that we can use a foreach statement to iterate through a collection which has been placed inside a class so i hope use the same technique for this problem. 我知道我们可以使用foreach语句来遍历放置在类中的集合 ,因此我希望对此问题使用相同的技术。 As i said in this case i am not working with a collection so Implementing the IEnumerable is a kind of meaningless idea. 正如我在这种情况下所说的,我不使用集合,因此实现IEnumerable是一种毫无意义的想法。 Is there any way to move among the members of class ? 有什么办法可以在全班同学之间移动吗?

I have tried this 我已经试过了

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

Implementing the IEnumerable 实施IEnumerable

public IEnumerator GetEnumerator()
{
    // ?!
}

You have to use Reflection, please look at 您必须使用反射,请看

How to get the list of properties of a class? 如何获取类的属性列表?

I added a new double? 我加了新的双打? property at your class. 课堂上的财产。

    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
            }
    }

You can use Reflection and Linq for this 您可以为此使用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);
}

Test 测试

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");

As you said you have properties, so why not use them as a Property ? 正如您所说的,您具有属性,那么为什么不将它们用作Property呢?

Use condition in get . get使用条件。 Return null while getting the value of property: 获取属性值时返回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