2012-07-30 114 views
0

我正在創建一個方法,它將循環實體對象上的屬性列表來檢查每個對象並在其中粘貼一些虛擬數據。這可能嗎?我嘗試低於但我卡住...(評論細節我不能工作,如何做)......如何獲得EntityObject類型的類型並將其與數據一起填充?

private static void SetAllNonNullableProperties(EntityObject airport, string uniqueMessage) 
{ 
    Type t = airport.GetType(); 
    PropertyInfo[] props = t.GetProperties(); 

    foreach (var prop in props) 
    { 
     //1) How do I see if this property is nullable? 
     //2) How do I tell the type so that I can stick a string/bool/datetime in it with dummy data? 
    } 
} 
+0

只是好奇,你爲什麼不以實體的構造themsel定義默認值VES? – 2012-07-31 21:17:34

回答

0

嗨Exitos, 試試這個:

public bool isNullableProperty(PropertyInfo p) 
{ 
    bool result = false; 
    foreach (object attr in p.GetCustomAttributes(typeof(EdmScalarPropertyAttribute), false)) 
     if (!(((EdmScalarPropertyAttribute)attr).IsNullable)) 
      result = true; 
    return result; 
} 

public void SetAllNonNullableProperties(System.Data.Objects.DataClasses.EntityObject airport) 
{ 
    Type t = airport.GetType(); 
    PropertyInfo[] props = t.GetProperties(); 

    foreach (PropertyInfo p in props) 
    { 
     if (isNullableProperty(p)) 
      // Now i know the secrets... ;) 

     if (p.PropertyType() == typeof(DateTime)) 
      // This property type is datetime 
     else if (p.PropertyType() == typeof(int)) 
      // And this type is integer 

    } 

} 
0

嘗試類似的東西:

using System; 
using System.Reflection; 

namespace ReflectionProp 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      Foo obj = new Foo { Name = "obj", Num = null, Price = null }; 
      Console.WriteLine(obj); 

      SetAllNonNullableProperties(obj, 100, 20); 

      Console.WriteLine(obj); 

      Console.ReadKey(); 
     } 

     private static void SetAllNonNullableProperties(Foo obj, int num, decimal dec) 
     { 
      Type t = obj.GetType(); 
      PropertyInfo[] props = t.GetProperties(); 

      foreach (var prop in props) 
      { 
       // check if property is nullable 
       if (Nullable.GetUnderlyingType(prop.PropertyType) != null) 
       { 
        // check if property is null  
        if (prop.GetValue(obj, null) == null) 
        { 
         if(prop.PropertyType == typeof(Nullable<int>)) 
          prop.SetValue(obj, num, null); 

         if (prop.PropertyType == typeof(Nullable<decimal>)) 
          prop.SetValue(obj, dec, null); 
        }      
       } 
      } 
     } 
    } 

    public class Foo 
    { 
     public Nullable<int> Num {get;set;} 
     public string Name { get; set; } 
     public Nullable<decimal> Price { get; set; } 

     public override string ToString() 
     { 
      return String.Format("Name: {0}, num: {1}, price: {2}", Name, Num, Price); 
     } 
    } 
} 
相關問題