我需要创建一个返回任何类型的泛型方法.
我的代码如下
//my callee method
public T getVal<T>(string key)
{
string result = ConfigurationManager.AppSettings[key].ToString();
return string.IsNullOrEmpty(result) ? (T)(object)result : default(T);
}
// and my caller's
getval<string>("somekey");
getval<int>("somekey1");
getval<bool>("somekey2")
Run Code Online (Sandbox Code Playgroud)
上面的调用工作正常.. 但是,我的要求是我需要将默认类型(例如:string)设置为callee方法.
eg: getval("somekey"); // callee should consider T as string by default and returns string type.
getval<int>("somekey2") //this is a normal call to the same callee which returns int type
Run Code Online (Sandbox Code Playgroud)