简体   繁体   English

返回值的类型类似于参数中的类型

[英]Return value's type like type in parameter

Can I create a method so that it returns the value of the type that I specify in parameters? 我可以创建一个方法,使其返回在参数中指定的类型的值吗? For example: 例如:

int i = Settings.Get("count", typeof(int));
string s = Settings.Get("count", typeof(string));
Guid g = Settings.Get("count", typeof(Guid));
public T Get<T> (string value)
{
     //read setting and cast


     //or if you have Setting.Get implementation
     return (T)Settings.Get("count", typeof(T));
}

now you can 现在你可以

int i = Get<int>("count");
string i = Get<string>("count");
Guid i = Get<Guid>("count");

You can do this by making the method generic: 您可以通过使方法通用来实现:

Settings.Get<T>(string name);

Inside the Get method you need to load the value and then cast it to T : 在Get方法内部,您需要加载值,然后将其强制转换为T

public T Get<T>(string value)
{
    object o = 1; // read setting;
    return (T)o;
}

And then call it: 然后调用它:

int i = Get<int>("count");

why don't you try generics like this 你为什么不尝试这样的泛型

   public T Get<T>(string value)
   {
     // do your stuff and cast the value
   }

where T is type T是类型

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

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