简体   繁体   中英

Reading datatype value from app.config

I have a generic method SampleMethod(param1, param2) and I need to call the method based on the config value. For example:

SampleMethod<long>(param1, param2);
SampleMethod<Guid>(param1, param2);

On the method call, type should change on the config value. I need to get the value from config file like app.config file.

public static Type RangeType
{
    get
    {
        Type rangeType;
        string rangeDataTypeString = ConfigurationManager.AppSettings["ShardRangeType"];

        switch (rangeDataTypeString.ToUpper())
        {
            case "LONG":
                rangeType = typeof (long);
                break;

            case "GUID":
                rangeType = typeof (Guid);
                break;

            default:
                rangeType = typeof (long);
                break;
        }

        return rangeType;
    }
}

When I try to call this based the configuration value and pass in this value to the above method like:

Type rangeType = Configuration.RangeType;
SampleMethod<rangeType>(param1, param2);

The rangeType in the above statement does not recognize as type, could someone suggest how to accomplish this. Thanks in advance!

如果“SampleMethod”方法存在于您想要调用它的同一个类中:

this.GetType().GetGenericMethod("SampleMethod",rangeType).Invoke(null,param1, param2);

Type arguments to invocations of generic methods are compiled. You can't put a variable into them. If you want to pass a Type as a parameter to the method, add it as a parameter to the method.

If you know that you have a very limited set of type arguments, you can create a set of conditional invocations (eg. with switch).

Otherwise you can use reflection to construct the appropriate generic method and invoke it (as shown in Reza's answer).

Without knowing exactly what you are doing with SampleMethod suggesting other alternatives about how to do it is impossible.

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