通用方法 - 无法将类型'string'隐式转换为T.

时间:2010-12-09 14:45:04

标签: c# generics interface

可能是一个简单的问题..

我有一个界面:

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

实施班:

    public class BasicFilenameSanitizer : ISanitizer
    {

        private readonly String m_replacementCharacter = String.Empty;

        public BasicFilenameSanitizer(String replacementCharacter_)
        {
            if (replacementCharacter_ == null)
            {
                throw new ArgumentNullException("replacementCharacter_");
            }

            m_replacementCharacter = replacementCharacter_;
        }


        public virtual T Sanitize<T>(T filename_)
        {
            if (filename_ == null)
            {
                throw new ArgumentNullException("filename_");
            }

            Regex invalidCharacterRegex =
                new Regex(String.Format("[{0}]", Regex.Escape(new string(System.IO.Path.GetInvalidFileNameChars()))));

//error occurs here
            return Regex.Replace(filename_.ToString(), invalidCharacterRegex.ToString(), m_replacementCharacter);
        }

}

4 个答案:

答案 0 :(得分:4)

在您的代码中,您将从通用类型返回string,这可能是任何

如果您想要通用返回类型,请将代码更改为:

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

public class BasicFilenameSanitizer : ISanitizer<string>

如果您只想总是返回string,则只需要更改方法返回类型:

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

public virtual string Sanitize<T>(T filename_)

答案 1 :(得分:2)

在我的特定情况下,以下代码生成了相同的错误:

return (T) someData;

什么帮助了我 - 用对象双重演绎:

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>();

答案 2 :(得分:0)

亚当,

您的界面不正确,请尝试:

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

[已编辑] - 添加示例.. 欢呼声..

答案 3 :(得分:0)

您的问题是方法Sanitize<T> has T as the return type, but the method actually returns a字符串from Regex.Replace`。

尝试更改方法以返回string

public virtual string Sanitize<T>(T filename_)

这意味着您需要在界面中更改方法以返回string