C#如何实现具体类不同的接口? [英] C# How to implement interface where concrete classes differs?

查看:290
本文介绍了C#如何实现具体类不同的接口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,抱歉vaque标题,但我不知道我的问题的好标题。

First, sorry for the vaque title, but I don't know a good title for my question.

在我的应用程序中,我使用标准。标准可以看作是对照。我有文本框,还有单选按钮和复选框。

In my application I use criteria. The criteria can be seen as controls. I have textboxes, but also radio buttons and check boxes.

我使用接口来实现这一点:

I use interfaces to achieve this:

ICriteria是所有条件类继承自的基接口。

ICriteria is the base interface where all criteria classes inherits from.

TextType继承自ICriteria。 RadioType也继承自ICriteria。但是,RadioType必须有选择。

TextType inherits from ICriteria. RadioType also inherits from ICriteria. But, RadioType must have choices.

两者,TextType和RadioType都有一些相同的属性。

Both, TextType and RadioType do have some properties which are the same.

我的问题是,我不知道我不知道如何实现这一点。我的意思是,我可以向ICriteria添加一些影响选择的方法和属性,但TextType也必须继承这些方法和属性。我不认为这很好,因为TextType没有选择。

My problem is, I don't know exactly how to implement this. I mean, I can add some methods and properties to ICriteria which affects choices, but then TextType has to inherit these methods and properties too. I don't think this is nice because TextType doesn't have choices.

实现这个的最佳方法是什么?

What is the best way to implement this?

推荐答案

为什么不使用接口层次结构

why not use a hierarchy of interfaces

public interface ICriteria
{
    void SomeCriteriaMethod();
}

public interface IChoices : ICriteria
{
    void SomeChoicesMethod();
}

然后像这样使用

foreach (ICriteria criteria in criterias)
{
    // something
    var choice = criteria as IChoices;
    if (choice != null)
        // do something else
}

这篇关于C#如何实现具体类不同的接口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆