【问题标题】:C#: Hide some model properties depending on the objectsC#:根据对象隐藏一些模型属性
【发布时间】:2018-03-19 17:33:10
【问题描述】:

所以基本上我有一个超类叫A,它的子类是B和C。还有一个模型类D。B类和C类共享同一个模型类D。

但是,有一个名为 [ID] 的属性不属于 C 类,但属于 B 类。

当我使用 C 类时,如何“隐藏”属性 [ID]?

【问题讨论】:

  • 共享类定义会让您更清楚地了解您想要实现的目标
  • “共享同一个模型类 D”是什么意思?请提供代码示例。
  • 请阅读关于如何提问的指南:stackoverflow.com/help/mcve
  • C 在这种情况下不是A。您可以将ID 字段分离到IHaveID 之类的接口中,B 自行实现。
  • @DanWilson 有一个模型类 D。B 类和 C 类都使用同一个模型类 D。

标签: c# model polymorphism .net-core


【解决方案1】:

使用接口:

interface IBComposite
{
    int ID {get;}
    string Name {get;set;}
}

interface ICComposite
{
    string Name {get;set;}
}

class D : IBComposite, ICComposite
{
    public int ID {get; set;}
    public string Name {get; set;}
}

class B
{
    private IBComposite myD;
    public B( IBComposite d ){ myD = d; }

    // Will "see" ID and Name on "myD"
}

class C
{
    private ICComposite myD;
    public C( ICComposite d ){ myD = d; }

    // Will "see" only Name on "myD"
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-07-17
    • 2016-05-20
    • 2011-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-01
    • 1970-01-01
    相关资源
    最近更新 更多