Using Generics to return a literal string or from Dictionary

前端 未结 5 1734
悲&欢浪女
悲&欢浪女 2021-01-27 04:51

I think I outsmarted myself this time. Feel free to edit the title also I could not think of a good one.

I am reading from a file and then in that file will be a string

相关标签:
5条回答
  • 2021-01-27 04:52

    Change:

    if (typeof(T) is string)
    

    to:

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

    The is operator is only valid on class instances. T is not actually an instance it is a type, therefor using is will not compile in your code because you need to compare 2 types. You can read more about it on msdn here.

    0 讨论(0)
  • 2021-01-27 05:04

    The line

    if (typeof(T) is string)
    

    will always return false sine the typeof operator gives a Type object. You should replace it with

    if (T is string)
    

    In addition you should look at the Convert.ChangeType method. It may be of help here.

    0 讨论(0)
  • 2021-01-27 05:05
    if(typeof(T) == typeof(string))
    {
        return (T)Parameter;
    }
    else
    {
        // convert the value to the appropriate type
    }
    
    0 讨论(0)
  • 2021-01-27 05:07

    Use typeof(T) == typeof(string)

    0 讨论(0)
  • 2021-01-27 05:08

    So here is the answer I came up with, I am a little worried about boxing and unboxing but it works for now

    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));
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题