[英]Creating an instance of a class with a name held in a string
我正在尋找一種以字符串作為名稱來初始化類的新實例的方法,以便稍后在列表中找到該特定實例。
目前,我有一些與此代碼類似的東西:
static List<ClassItem> classList = new List<ClassItem>();
private void updateClassList(Stream stream)
{
Message = Recieve(stream);
Interact(Message); //get the number of Classes about to be recieved
string ID;
string state;
for(int i = 0; i < numberOfClasses; i++)
{
Message = Recieve(stream);
interpretClassProperties(Message, out ID, out State);
ClassItem ID = new ClassItem(ID, state); //incorrect code
classList.Add(ID); //add new instance to list
}
}
顯然,這是行不通的,因為我不能使用變量來初始化類實例,但是從邏輯上講,它顯示了我想要實現的目標。 每個循環都會將ClassItem
的實例(具有適當的ID值作為名稱)添加到classList
以便稍后找到它。
為了實現這一目標,我應該考慮什么?
感謝您提供任何反饋意見,包括在以這種方式解決問題時可能遇到的未來問題的任何警告。 (即按名稱在List中查找類實例)。
使用Activator.CreateInstance:
public static ObjectHandle CreateInstance(
string assemblyName,
string typeName
)
您知道您的程序集名稱,並收到類名稱(類型名稱)。
MSDN: https : //msdn.microsoft.com/zh-CN/library/d133hta4(v = vs.110) .aspx
樣例代碼:
static List<object> classList = new List<object>();
private void updateClassList(Stream stream)
{
Message = Recieve(stream);
Interact(Message); //get the number of Classes about to be recieved
string id;
for(int i = 0; i < numberOfClasses; i++)
{
Message = Recieve(stream);
interpretClassProperties(Message, out id);
classList.Add(Activator.CreateInstance("AssemblyName", id).Unwrap());
}
}
您正在尋找類似這樣的東西嗎? 但是請注意,除非您確定要從靜態列表中取消引用實例,否則這可能會及時造成內存噩夢。
public class ClassWithIds
{
public static List<ClassWithIds> Instances = new List<ClassWithIds>();
private static int _idSeed = 0;
private readonly string _name;
public string Name
{
get
{
return _name;
}
}
private static int NextId()
{
return Interlocked.Increment(ref _idSeed);
}
public ClassWithIds()
{
_name = this.GetType().FullName + " Number " + NextId();
Instances.Add(this);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.