Creating a generic method in C#

后端 未结 6 1260
耶瑟儿~
耶瑟儿~ 2020-12-04 09:45

I am trying to combine a bunch of similar methods into a generic method. I have several methods that return the value of a querystring, or null if that querystring does not

6条回答
  •  情话喂你
    2020-12-04 09:57

    You can use sort of Maybe monad (though I'd prefer Jay's answer)

    public class Maybe
    {
        private readonly T _value;
    
        public Maybe(T value)
        {
            _value = value;
            IsNothing = false;
        }
    
        public Maybe()
        {
            IsNothing = true;
        }
    
        public bool IsNothing { get; private set; }
    
        public T Value
        {
            get
            {
                if (IsNothing)
                {
                    throw new InvalidOperationException("Value doesn't exist");
                }
                return _value;
            }
        }
    
        public override bool Equals(object other)
        {
            if (IsNothing)
            {
                return (other == null);
            }
            if (other == null)
            {
                return false;
            }
            return _value.Equals(other);
        }
    
        public override int GetHashCode()
        {
            if (IsNothing)
            {
                return 0;
            }
            return _value.GetHashCode();
        }
    
        public override string ToString()
        {
            if (IsNothing)
            {
                return "";
            }
            return _value.ToString();
        }
    
        public static implicit operator Maybe(T value)
        {
            return new Maybe(value);
        }
    
        public static explicit operator T(Maybe value)
        {
            return value.Value;
        }
    }
    

    Your method would look like:

        public static Maybe GetQueryString(string key) where T : IConvertible
        {
            if (String.IsNullOrEmpty(HttpContext.Current.Request.QueryString[key]) == false)
            {
                string value = HttpContext.Current.Request.QueryString[key];
    
                try
                {
                    return (T)Convert.ChangeType(value, typeof(T));
                }
                catch
                {
                    //Could not convert.  Pass back default value...
                    return new Maybe();
                }
            }
    
            return new Maybe();
        }
    

提交回复
热议问题