0

我正在尝试创建一种方法,该方法将循环实体对象上的属性列表,检查每个属性并在其中粘贴一些虚拟数据。这可能吗?我的尝试在下面,但我被卡住了......(评论详细说明了我无法解决的问题)......

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

2 回答 2

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

    }

}
于 2012-07-30T16:28:32.980 回答
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);
        }
    }
}
于 2012-07-30T16:48:48.197 回答