在C#中为IList赋值 [英] assign values to IList in C#

查看:106
本文介绍了在C#中为IList赋值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个枚举和课程

i have one enum and class

public enum rank
{
gold,
silver,
bronze
}

public class studentdet
{
public string name{get;set;}
public IList<rank> studentrank{get; set;}

}



如何为studentdet类及其分配值属性IList?


how to assign values to studentdet class and its property IList?

推荐答案

我认为您打算将该物业声明为:



公共IList学生< rank> {得到; set;}



a。虽然您可以将属性声明为IList< SomeType>,但在分配List< SomeType>时使用它。就像你使用它一样,如果你把它声明为List< SomeType>



这不是一个好习惯:重要的是你要记住,谢谢谢尔盖说,IList是一个接口,List是一个实现该接口的对象。在IList和List的情况下,将List转换为IList接口没有任何好处......在其他情况下,实际上有一些用于将Object转换为接口。



b。虽然对我来说没有意义,为什么一个学生会有一个'排名列表,我会假设你有这样的理由:
I think you meant to declare the Property as:

public IList studentranks<rank> {get; set;}

a. while you can declare a Property as an IList<SomeType>, and use it when you assign a List<SomeType> to it just as you would use it if you had declared it as List<SomeType>

That's not good practice: it's important for you to keep in mind, as Sergey says, that an IList is an Interface, and that List is an object that implements that Interface. In the case of IList and List, there's nothing to be gained by casting the List to its IList interface ... in other cases there are, indeed, uses in casting an Object to an Interface.

b. while it doesn't make sense to me why one student would have a list of 'rank, I'll assume you have a reason for that:
public enum Rank { Gold, Silver, Bronze }

public class StudentDet
{
    public string StudentName { get; set; }
    public List<Rank> StudentRanks { get; set; }

    // optional entry of rank(s) here
    public StudentDet(string name, params Rank[] ranks)
    {
        StudentName = name;
        AddRanks(ranks);
    }

    public void AddRanks(params Rank[] ranks)
    {        
        if(ranks.Length > 0)
        {
            // lazy initialization here
            if(StudentRanks == null) StudentRanks = new List<Rank>();

            StudentRanks.AddRange(ranks);
        }        
    }
}


这篇关于在C#中为IList赋值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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