Reflection 反射

https://stackoverflow.com/questions/5122201/get-a-member-object-using-reflection-or-some-other-way

public static ConcurrentDictionary<Tuple<Type, string>, 
        Func<object, object[], object>> ReflectionCache
    {
        get
        {
            if (_ReflectionCache==null) {
                _ReflectionCache = new ConcurrentDictionary<Tuple<Type, string>,
                  Func<object, object[], object>>();
            }
            return _ReflectionCache;
        }
    } private static ConcurrentDictionary<Tuple<Type, string>, 
         Func<object, object[], object>> _ReflectionCache = null;

    public static object GetCachedProperty(object obj, string name)
    {
        Func<object,object[],object> del;
        if (!ReflectionCache.TryGetValue(Tuple.Create<Type,string>(obj.GetType(),
          name), out del)) {
            MemberInfo memberInfo = 
               (MemberInfo)obj.GetType().GetMember(name).GetValue(0);
            PropertyInfo prop = null;
            FieldInfo fld = null;

            switch(memberInfo.MemberType) {
            case MemberTypes.Field:
                fld = obj.GetType().GetField(name);
                break;
            case MemberTypes.Property:
                prop = obj.GetType().GetProperty(name);
                break;
            }

            if (prop == null && fld == null)
            {
                throw new Exception("No property or field named '" + name 
                 + "' could be found in the context parent.");
            }
            if (prop!=null) {
                prop= obj.GetType().GetProperty(name);
                del = prop.GetValue;
            } else {
                fld = obj.GetType().GetField(name);
                del = delegate(object cls,object[] index) {
                    return fld.GetValue(cls);
                };
            }

            ReflectionCache[Tuple.Create<Type,string>(obj.GetType(),name)]=del;
        }
        return(del(obj,null));
    }

 

 

http://e-troy.blogspot.com/2014/03/c-reflection-part-1-typeinvokemember.html

//建立使用者參數

User user = new User();
user.Name = "E-Troy";
 
Print(user);

//建立產品參數
Product product = new Product();
product.Id = 9487;
product.ProName = "E-Troy's SuperComputer";
 
Print(product);


//將結果呈現
Type ot = objVo.GetType();
 
List<string> names = (List<string>)ot.InvokeMember(
    "PropertyNames",
    System.Reflection.BindingFlags.GetProperty,
     null, objVo, new object[] { });
 
foreach (string name in names)
{
   this.resultLabel.Text = objType.InvokeMember(
   "GetPropertyValue",
   System.Reflection.BindingFlags.InvokeMethod,
   null, ot, new object[] { name }) + "\n";
 
}
查看原文 >>
相关文章