【问题标题】:Problem building a generic inherited class in C#在 C# 中构建泛型继承类的问题
【发布时间】:2019-11-30 18:57:56
【问题描述】:

我写了以下类,我不知道为什么行:

return new PersonEncrypterDecrypter()

在类EncrypterDecrypterBuilder<T> 中不起作用。

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

这里是代码链接:

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

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

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

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

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

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

EncrypterDecrypterBuilder类中

【问题讨论】:

    标签: c# generics abstraction


    【解决方案1】:

    第一个问题是static class EncrypterDecrypterBuilder 方法。静态构造函数 不能有参数也不能返回值。看起来你只想有一个静态方法。重命名此方法。此外,您需要在 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

    【讨论】:

    • 在进行更改(名称和演员表)之后,我在正文中写了以下行: EncrypterDecrypter e1 = EncrypterDecrypterBuilder.Builder(eEncryptersDecrypters.Person);但在运行时我得到一个无效的转换异常
    • T 是实体。您不能将 EncrypterDecrypter 转换为 EncrypterDecrypter。使用公共接口 EncrypterDecrypter where T : Entity
    • 您想在本主题中涵盖很多内容(与您的第一个问题无关)。从这篇文章开始docs.microsoft.com/en-us/dotnet/csharp/programming-guide/…
    • 我按照您的建议做了,但出现以下错误:imgur.com/8EexTtj
    • 非常感谢它有效,我会阅读您提供的文章以便理解。
    猜你喜欢
    • 2011-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多