本文介绍了在C#中,接口是否可以实例化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读 here 。我在TreeList.cs中找到 private ITreeModel _model;

namespace Aga.Controls.Tree
{
    public class TreeList: ListView
    {
        #region Properties
        //...
        private ITreeModel _model;
        public ITreeModel Model
        {
            //...
        }
        //...
    }
}

和ITreeModel是ITreeModel.cs中的一个接口:

and the ITreeModel is a interface in ITreeModel.cs:

namespace Aga.Controls.Tree
{
    public interface ITreeModel
    {
        /// <summary>
        /// Get list of children of the specified parent
        /// </summary>
        IEnumerable GetChildren(object parent);

        /// <summary>
        /// returns wheather specified parent has any children or not.
        /// </summary>
        bool HasChildren(object parent);
    }
}

_model 是一个实例化对象?

已编辑

TreeList.cs

namespace Aga.Controls.Tree
{
    public class TreeList: ListView
    {
        #region Properties

        /// <summary>
        /// Internal collection of rows representing visible nodes, actually displayed in the ListView
        /// </summary>
        internal ObservableCollectionAdv<TreeNode> Rows
        {
            get;
            private set;
        } 

        private ITreeModel _model;
        public ITreeModel Model
        {
            get { return _model; }
            set 
            {
                if (_model != value)
                {
                    _model = value;
                    _root.Children.Clear();
                    Rows.Clear();
                    CreateChildrenNodes(_root);
                }
            }
        }

        private TreeNode _root;
        internal TreeNode Root
        {
            get { return _root; }
        }
        //....
    }
}

}

Edited2

某处:

public partial class RegistrySample : UserControl
{
    public RegistrySample()
    {
        InitializeComponent();
        _tree.Model = new RegistryModel();
    }
}

class RegistryModel:ITreeModel

推荐答案

当然可以这样做,但底层对象必须实现此接口。所以你可以做类似的事情

Of course you can do this, but underlying object must implement this Interface. So you can do something like

ITreeModel _model  = new TreeModel();

其中

public class TreeModel:ITreeModel
{
  ...
}

这篇关于在C#中,接口是否可以实例化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!