使用Generics返回文字字符串或从Dictionary

我想我这次出局了。 随意编辑标题我也想不出一个好的标题。

我正在读取一个文件然后在该文件中将是一个字符串,因为它像一个xml文件。 但是在文件中将是一个文字值或“命令”来从workContainer获取值

所以

me@company.com 

要么

 [? MyEmail ?] 

我想做什么,而不是写在各处,把它放在一个通用的function

所以逻辑是

 If Container command grab from container else grab string and convert to desired type Its up to the user to ensure the file is ok and the type is correct 

另一个例子是

所以

 3 

要么

 [? NumberOfSales ?] 

这是我开始研究的程序

 public class WorkContainer:Dictionary { public T GetKeyValue(string Parameter) { if (Parameter.StartsWith("[? ")) { string key = Parameter.Replace("[? ", "").Replace(" ?]", ""); if (this.ContainsKey(key)) { return (T)this[key]; } else { // may throw error for value types return default(T); } } else { // Does not Compile if (typeof(T) is string) { return Parameter } // OR return (T)Parameter } } } 

电话会是

  mail.To = container.GetKeyValue("me@company.com"); 

要么

  mail.To = container.GetKeyValue("[? MyEmail ?]"); int answer = container.GetKeyValue("3"); 

要么

  answer = container.GetKeyValue("[? NumberOfSales ?]"); 

但它不编译?

 if(typeof(T) == typeof(string)) { return (T)Parameter; } else { // convert the value to the appropriate type } 

这条线

 if (typeof(T) is string) 

将始终返回false sine,typeof运算符给出一个Type对象。 你应该用它替换它

 if (T is string) 

另外,您应该查看Convert.ChangeType方法。 这可能会有所帮助。

使用typeof(T) == typeof(string)

更改:

 if (typeof(T) is string) 

至:

 if (typeof(T) == typeof(String)) 

is运算符仅对类实例有效。 T实际上并不是一个类型的实例,因此你不需要在代码中编译,因为你需要比较两种类型。 您可以在这里阅读有关它的更多信息。

所以这是我提出的答案,我有点担心拳击和拆箱但它现在有效

 public class WorkContainer:Dictionary { public T GetKeyValue(string Parameter) { if (Parameter.StartsWith("[? ")) { string key = Parameter.Replace("[? ", "").Replace(" ?]", ""); if (this.ContainsKey(key)) { if (typeof(T) == typeof(string) ) { // Special Case for String, especially if the object is a class // Take the ToString Method not implicit conversion return (T)Convert.ChangeType(this[key].ToString(), typeof(T)); } else { return (T)this[key]; } } else { return default(T); } } else { return (T)Convert.ChangeType(Parameter, typeof(T)); } } }