简体   繁体   中英

getting current value reflection c#

i have used the following code to change the current value for the current field value as

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

connectionStringField.SetValue(this, connectionString);  

but my query is to get current value of connectionstringfied...

i tried the below code as

getvalue(obj ss);

waiting for your valuable esponses

it throws me null values

If connectionStringField has found the field (ie it is in the base type and is called "_sqlConnectionString", then it should just be:

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

?

However, using reflection to talk to non-public fields is... unusual.

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 is a cache to avoid reflection performance issue

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);
    }

I used the same trick for setters

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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