简体   繁体   中英

manipulating members of a class using foreach statement

My class has a bunch of nullable double properties. At run time some of them have 0 value and i am going to set them null before sending action. 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. As i said in this case i am not working with a collection so Implementing the IEnumerable is a kind of meaningless idea. 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

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

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 ?

Use condition in get . Return null while getting the value of property:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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