在迭代对象列表时避免多个"if"语句c#

Ida*_*nis 2 c# oop types casting object

我有各种类生成excel图.

每个类生成一个不同的图.

它们都共享相同的私有变量,具有不同的值.

我希望编写一个通用代码,以防止"if"语句确定它是哪个图形.

以下是其中一个类的示例:

using System;

namespace GraphsGenerator
{
   public class GraphOne
   {
       #region Private Members

       private string m_baseDir = "";
       private static string m_graphName = "GraphOne";
       private string m_imageFile = m_graphName + Utils.ImageExtension;

       #endregion Private Members

       #region Properties

       public string BaseDir
       {
           set { m_baseDir = value; }
       }
       public string GraphName
       {
           get { return m_graphName; }
       }
       public string ImageFile
       {
           get { return m_imageFile; }
           set { m_imageFile = value; }
       }

       #endregion Properties

       #region Constructor


       public HandTrackingGraphs(string baseDir)
       {
           m_baseDir = baseDir;
       }

       #endregion Constructor
   }
 }
Run Code Online (Sandbox Code Playgroud)

我试着在我的主要部分做到这一点:

List<object> listOfGraphs = new List<object>();
listOfGraphs.Add(new GraphOne());
listOfGraphs.Add(new GraphTwo());
listOfGraphs.Add(new GraphThree());

foreach (object currentGraph in listOfGraphs)
{
   string imageFile = currentGraph.ImageFile;
}
Run Code Online (Sandbox Code Playgroud)

但当然这不可能.

有任何想法吗?

Jon*_*eet 8

它们都共享相同的私有变量,具有不同的值.

它们都应该实现相同的接口,从而暴露ImageFile属性.例如:

public interface IGraph
{
    // TODO: Consider making this read-only in the interface...
    public string ImageFile { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

然后你可以:

List<IGraph> listOfGraphs = new List<IGraph>();
listOfGraphs.Add(new GraphOne());
listOfGraphs.Add(new GraphTwo());
listOfGraphs.Add(new GraphThree());

foreach (IGraph currentGraph in listOfGraphs)
{
   string imageFile = currentGraph.ImageFile;
}
Run Code Online (Sandbox Code Playgroud)

您也可以使用抽象基类而不是接口.这有点限制性,但这意味着图表也可以共享通用实现.

(如果你真的想要灵活性而且还需要代码重用,你甚至可以创建一个由抽象基类实现的接口.)