Using Generics to return a literal string or from Dictionary

前端 未结 5 1788
刺人心
刺人心 2021-01-23 08:04

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-23 08:44

    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
    {
        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));
            }
        }
    }
    

提交回复
热议问题