在 C# 中构建泛型继承 class 时出现问题

Problem building a generic inherited class in C#

我写了以下 classes 但我不知道为什么这行:

return new PersonEncrypterDecrypter()

在classEncrypterDecrypterBuilder<T>里面是不行的。

据说不允许强制转换,但我看不出有任何理由认为这是一个问题。

这是代码的link:

http://coliru.stacked-crooked.com/a/2f10c6bb11a3c79d

编辑:做了一些更改(代码的 link 已更新)。

我写了一个这样的main方法:

EncrypterDecrypter<Entity>e1 = 
EncrypterDecrypterBuilder<Entity>.Builder(eEncryptersDecrypters.Person);
 Dictionary<string, string> dic = e1.DataDecrypter(test);

我在尝试执行第一行时得到 System.InvalidCastException

return (EncrypterDecrypter<T>)(new PersonEncrypterDecrypter())

这是在 class EncrypterDecrypterBuilder

第一个问题是 static class EncrypterDecrypterBuilder 方法。静态构造器 不能有参数,也不能 return 值。看起来您只想拥有一个静态方法。重命名此方法。此外,您需要在 return 子句

中转换对象
public static class EncrypterDecrypterBuilder<T> where T : Entity
{
    public static EncrypterDecrypter<T> EncrypterDecrypterBuilderSomeNewName()
    {

        return (EncrypterDecrypter<T>)(new PersonEncrypterDecrypter());
    }
}

查看所有代码:http://coliru.stacked-crooked.com/a/6a3d3fef3b7af7f2