首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何实现具有接口属性的工具?

如何实现具有接口属性的工具?
EN

Stack Overflow用户
提问于 2022-01-13 02:27:55
回答 1查看 22关注 0票数 0

我希望一个类具有另一个类的属性,但是我希望外部类和内部类都实现一个接口,外部接口为内部的类提供一个属性。

这是我试过的密码。

代码语言:javascript
复制
interface IMainBody
{
    ISubProperty subProperty { get; set; }
}
interface ISubProperty
{
    string somethingHere { get; set; }
}
class MainBody : IMainBody // Error CS0738  'MainBody' does not implement interface member 'IMainBody.subProperty'. 'MainBody.subProperty' cannot implement 'IMainBody.subProperty' because it does not have the matching return type of 'ISubProperty'.
{
    public SubProperty subProperty { get; set; }
}
class SubProperty : ISubProperty
{
    public string somethingHere { get; set; }
}

我知道我需要像这样的通用接口

代码语言:javascript
复制
interface IMainBody<T>
    where T : ISubProperty
{
    T subProperty { get; set; }
}
interface ISubProperty
{
    string somethingHere { get; set; }
}

但是我不喜欢这样做,因为这意味着一旦有了这样的多个属性,代码就会变得非常混乱。

有人知道其他的解决办法吗?

EN

回答 1

Stack Overflow用户

发布于 2022-01-13 02:50:41

代码语言:javascript
复制
class MainBody : IMainBody 
{
    public SubProperty subProperty { get; set; }
    ISubProperty IMainBody.subProperty { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70690724

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档