1

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

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

connectionStringField.SetValue(this, connectionString);  

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

我尝试了以下代码

getvalue(obj ss);

等待您的宝贵回复

它向我抛出空值

4

3 回答 3

2

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

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

?

但是,使用反射与非公共领域对话是……不寻常的。

于 2012-11-08T09:48:51.997 回答
1
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 是避免反射性能问题的缓存

于 2012-11-08T10:18:29.277 回答
0
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);
    }

我对二传手使用了相同的技巧

于 2012-11-08T11:08:14.770 回答