[英]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
}
}
您可以為此使用Reflection和Linq
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.