Generic Method - Cannot implicitly convert type 'string' to T

前端 未结 4 1250
后悔当初
后悔当初 2021-01-15 04:41

May be a simple question..

I have an interface:

public interface ISanitizer
{
    T Sanitize(T data_);
}

And an implementi

4条回答
  •  清酒与你
    2021-01-15 05:26

    In my particular case the following code generated the same error:

    return (T) someData;
    

    What helped me out - double cast with object:

    E.g:

        static T MyFunction() {
            string s = "test";
    
            if (typeof(T) == typeof(byte[]))
                return (T)(object)System.Text.Encoding.ASCII.GetBytes(s);
            else if (typeof(T) == typeof(string))
                return (T)(object)s;
            else throw new Exception();
        }
    

    ...

                var ba = MyFunction();
                var bs = MyFunction();
    

提交回复
热议问题