基本上我有一个带有子类的类(或嵌套类,无论它叫什么,都属于内部类)
我不知道为什么我无法访问(或者我猜列表中不包含嵌套类) 嵌套类。
public static List<Tag> Tags = new List<Tag>();
//cureently selected tag,also random percentage related data
public class Tag
{
public string name = null;
public int dupe = 0;
public int Tagindex = 0;
public int URLindex = 0;
public class Type
{
public bool isArtist = false;
public bool isGroup = false;
public bool isTag = false;
public bool isURL = false;
}
public class Score
{
// 0~10, sort them out!
public bool isRated = false; //make true if user modifies score
public int Story = 0;
public int Reality = 0;
public int Drawing = 0;
public int memetic = 0;
public string msg = null;
}
dataGridView1.Rows.Add(gVar.Tags[i].Tagindex,gVar.Tags[i].name/*valid*/, gVar.Tags[i].Type.isArtist/*invalid*/);
//also invalid
Tag t1 = new Tag();
t1.Type.isArtist = true;
gVar.Tags.Add(t1);
答案 0 :(得分:1)
嵌套类只是该类的声明,就像未嵌套该类一样。 您必须实例化该类型的对象才能访问其属性之一。 例如:
public class Tag
{
public string name = null;
public int dupe = 0;
public int Tagindex = 0;
public int URLindex = 0;
public Score Score { get; } = new Score() // declare a property of the nested type, and instantiate an object
public class Type
{
public bool isArtist = false;
public bool isGroup = false;
public bool isTag = false;
public bool isURL = false;
}
public class Score
{
// 0~10, sort them out!
public bool isRated = false; //make true if user modifies score
public int Story = 0;
public int Reality = 0;
public int Drawing = 0;
public int memetic = 0;
public string msg = null;
}
以及用法:
Tag t1 = new Tag();
t1.Score.Story = 3;
顺便说一句,不建议使用公共字段,而应使用属性(例如上面代码中的Score属性)。