繁体   English   中英

获取当前值反射c#

[英]getting current value reflection c#

我使用以下代码将当前字段值的当前值更改为

FieldInfo connectionStringField = GetType().BaseType.GetField("_sqlConnectionString", BindingFlags.Instance | BindingFlags.NonPublic);  

connectionStringField.SetValue(this, connectionString);  

但我的查询是获取connectionstringfied的当前值...

我尝试了以下代码

getvalue(obj ss);

等待你宝贵的回应

它会抛出我的空值

如果connectionStringField找到了该字段(即它是基类型并被称为“_sqlConnectionString”,那么它应该只是:

string connectionString = (string)connectionStringField.GetValue(this);

但是,使用反射与非公共领域交谈是不寻常的。

public static string GetPropertyValue<T>(this T obj, string parameterName)
    {
        PropertyInfo[] property = null;
        Type typ = obj.GetType();
        if (listPropertyInfo.ContainsKey(typ.Name))
        {
            property = listPropertyInfo[typ.Name];
        }
        else
        {
            property = typ.GetProperties();
            listPropertyInfo.TryAdd(typ.Name, property);
        }
        return property.First(p => p.Name == parameterName).GetValue(obj, null).ToString();
    }

listPropertyInfo是一个缓存,以避免反射性能问题

public static void SetPropertyValue<T>(this T obj, string parameterName, object value)
    {
        PropertyInfo[] property = null;
        Type typ = obj.GetType();
        if (listPropertyInfo.ContainsKey(typ.Name))
        {
            property = listPropertyInfo[typ.Name];
        }
        else
        {
            property = typ.GetProperties();
            listPropertyInfo.TryAdd(typ.Name, property);
        }
        if (value == DBNull.Value)
        {
            value = null;
        }
        property.First(p => p.Name == parameterName).SetValue(obj,value, null);
    }

我对制定者使用了相同的技巧

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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