使用Generics返回文字字符串或从Dictionary <string,object =“”> </string,>

时间:2010-04-22 13:50:43

标签: c# generics

我想这次我已经超过了自己。随意编辑标题我也想不出好的。

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

所以

<Email>me@company.com</Email>

<Email>[? MyEmail ?]</Email>

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

所以逻辑是

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 

所以另一个例子是

所以

<Answer>3</Answer>

<Answer>[? NumberOfSales ?]</Answer>

这是我开始处理的程序

public class WorkContainer:Dictionary<string, object>
{
    public T GetKeyValue<T>(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<string>("me@company.com");

  mail.To = container.GetKeyValue<string>("[? MyEmail ?]");

  int answer = container.GetKeyValue<int>("3");

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

但它没有编译?

5 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:0)

该行

if (typeof(T) is string)

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

替换它
if (T is string)

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

答案 2 :(得分:0)

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

答案 3 :(得分:0)

变化:

if (typeof(T) is string)

为:

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

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

答案 4 :(得分:0)

所以这就是我想出的答案,我有点担心拳击和拆箱但它现在适用

public class WorkContainer:Dictionary<string, object>
{
    public T GetKeyValue<T>(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));
        }
    }
}