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

前端 未结 4 1251
后悔当初
后悔当初 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:21

    Adam,

    your interface is incorrect, try:

    public interface ISanitizer<T, TA>
    {
        T Sanitize(TA data);
    }
    
    public class BasicFilenameSanitizer<T, TA> : ISanitizer<T, TA>
    {
        public virtual T Sanitize(TA data)
        {
            throw new NotImplementedException();
        }
    }
    
    public class Test : BasicFilenameSanitizer<int, string>
    {
        public override int Sanitize(string data)
        {
            return data.Length;
        }
        // a little test func...
        public void TestFunc()
        {
            int result = this.Sanitize("fred");
            Console.Write(result);
        }
    }
    

    [edited] - to add example.. cheers..

    0 讨论(0)
  • 2021-01-15 05:26

    In your code you are returning a string from a generic type which could be anything.

    Change your code to this if you want a generic return type:

    public interface ISanitizer<T>
    {
        T Sanitize(T data_);
    }
    
    public class BasicFilenameSanitizer : ISanitizer<string>
    

    If you simply want to always return a string you only need to change the method return type:

    public interface ISanitizer
    {
        string Sanitize<T>(T data_);
    }
    
    public virtual string Sanitize<T>(T filename_)
    
    0 讨论(0)
  • 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<T>() {
            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<byte[]>();
                var bs = MyFunction<string>();
    
    0 讨论(0)
  • 2021-01-15 05:35

    Your problem is that the method Sanitize<T> hasTas the return type, but the method actually returns astringfromRegex.Replace`.

    Try changing the method to return a string instead:

    public virtual string Sanitize<T>(T filename_)
    

    That means you need to change your method in the interface to return string as well.

    0 讨论(0)
提交回复
热议问题