2012-03-06 129 views
0

我有即时通讯与挣扎了C#的问题。我正在设计一门课,但我不太熟悉oop。是否可以定义与类本身类型相同的列表?例如说我有一个狗类:类的同一对象的类定义

public class Dog 
{ 
    public string _name {get; set;}; 

    public Dog (string, name) 
    { 
     _name = name; 
    } 

    public List<Dog> listOfDogs() 
    { 
     // blah blah 
    } 
} 

这样的结构可能吗?如果是这样,怎么样?这是做这种事的正确方法吗?或者我应该创建另一个辅助类,通过创建单独的狗对象来简单地构建狗列表?

感谢

+0

它工作正常。你尝试过时有没有为你工作? – 2012-03-06 17:21:49

回答

0

短answert:是的,它是。

这使得在许多情况下的感觉。 A Dog可能与OOP世界中的其他狗相关联。

此外,让我建议你一些其他微小的改进:

public class Dog 
{ 
    public string Name { get; set; } // PascalCase is a convention here 

    public Dog(string name) 
    { 
    Name = name; 
    } 

    public IList<Dog> listOfDogs() // try to expose interfaces whenever possible 
    { 
    // blah blah 
    } 
} 

尤其是界面事情值得大量的阅读,如果你是新的OOP。有几个不同的列表实现,OOP帮助你隐藏这些所谓的“实现细节”。稍后,您可以使用Dog[]而不是List<Dog>而不更改班级的消费者。两者都执行IList<Dog>。该详细在很多地方描述

它的东西。有书籍,文章,或者这个问题上的SO:What do programmers mean when they say, "Code against an interface, not an object."?

0

是否可以定义相同类型的类本身的类型的列表?
这样的结构可能吗?

是的,这是完全合法的。问题在于它是否适用于您的应用程序。

如果是这样,怎么样?这是做这种事的正确方法吗?

你这样做的方式很好,但通常它会被声明为属性而不是方法。

或者我应该创建另一个辅助类,简单地通过创建单独的狗对象来建立狗列表?

这取决于你想要做什么...很难确切地说出你的目标是什么。

0

这样做:

public class Dogs : List<Dog> { 
    // your additional methods/properties/etc go here 
    // every object of this list will be of the type "Dog" 
    // and you cannot add any type other than the type "Dog" to this list 
} 

希望帮助

编辑: 我希望我理解正确你的问题...

你也可能要你的类“狗”的定义改成这样:

public class Dog { 
    public Dog(string name) { 
     this.Name = name; 
    } 

    public string Name { get; set; } 
} 
0

是的,这是完全合法的一类指本身具有作为成员的自身情况。

然而,这可能不是你想要的这个特定问题的设计。对于一只狗有其他狗的名单是不合逻辑的(在我看来)。