课的一些问题 [英] some problem with classes
问题描述
你好。
我有7个课程,Topaz1,Topaz2,Topaz3 ...... Topaz7都来自Topaz课程。
我需要制作一个根据起始编号和结束编号创建Topaz列表的功能。例如,如果起始编号为3且结束编号为5,则列表应包含Topaz4,Topaz5的元素,如果起始编号为1且结束编号为4,则列表将包含Topaz2类的元素, Topaz3,Topaz4。
如何执行这样的代码?我实际上已经完成了我可能拥有的每一个想法以及长期的谷歌搜索。
Hello.
I have a 7 classes, Topaz1, Topaz2, Topaz3... Topaz7 that all derive from class "Topaz".
I need to make a function that creates a list of "Topaz" according to a starting number and an ending number. For example, if the starting number is 3 and the ending number is 5 then the list should have elements of Topaz4, Topaz5, and if the starting number is 1 and the ending number is 4 the list will have the elements of the classes Topaz2, Topaz3, Topaz4.
How do I execute such a code? I have literally gone through every idea I possibly had and a long google search.
推荐答案
这让我觉得这是一种非常糟糕的做事方式 - 但它非常简单,取决于你究竟想要做什么。
假设你有这样的课程:
This strikes me as a very poor way to do things - but it's pretty simple, depending on what exactly you are trying to do.
Assuming you have classes thus:
public abstract class Topaz { }
public class Topaz1 : Topaz { }
public class Topaz2 : Topaz { }
public class Topaz3 : Topaz { }
public class Topaz4 : Topaz { }
public class Topaz5 : Topaz { }
public class Topaz6 : Topaz { }
public class Topaz7 : Topaz { }
然后如果你正在过滤现有的实例列表,只包含您想要的类型:
Then if you are filtering an existing list of instances to just the types you want:
private List<Topaz> FilterThem(IEnumerable<Topaz> source, int lo, int hi)
{
return source.Where(s => InRange(s, lo, hi)).ToList();
}
private bool InRange(Topaz t, int lo, int hi)
{
int n = int.Parse(t.GetType().Name.Substring(5));
return (lo < n && n <= hi);
}
如果你想创建实例,那就太麻烦了:
If you are trying to create instances, that's a lot more messy:
private List<Topaz> CreateThem(int lo, int hi)
{
List<Topaz> list = new List<Topaz>();
System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();
string name = assembly.FullName.Split(',')[0] + ".Topaz";
for (int i = lo + 1; i <= hi; i++)
{
list.Add((Topaz)assembly.CreateInstance(name + i));
}
return list;
}
但我仍然认为你在这里做出了一些糟糕的设计决定!
But I still think you have made some poor design decisions here!
这篇关于课的一些问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!