[英]How can I populate a class based on an array?
我有一個數據數組,其中可以包含1到10個值。 基於數組中值的數量,我想從10個不同的類中選擇1個,並將數組的值放在類對象中。
這就是我到目前為止
Array[] ar;
ar = PopulateTheArray();
int cnt = ar.Count();
Object ob = Activator.CreateInstance(null, "MyObject" + cnt);
有10個這樣的MyObject類,
public class MyObject1
{
public string Column1 { get; set; }
}
public class MyObject2
{
public string Column1 { get; set; }
public string Column2 { get; set; }
}
public class MyObject3
{
public string Column1 { get; set; }
public string Column2 { get; set; }
public string Column3 { get; set; }
}
and so on.....
由於對象是動態創建的,如何循環拋出數組以填充對象?
這個類的架構確實看起來很奇怪。 看來您有一個約定 ,類MyObjectX
將完全具有名為Column1
- ColumnX
X屬性。 我以前從未見過這種情況,也沒有想到任何合適的方案。
無論如何,我強烈建議您描述問題領域和當前體系結構,以便其他人可以評估其適用性並提出替代方案。 例如, 可能只需要編寫一個封裝數組(或其他集合)的類即可:
public class MyObject
{
public string[] Columns { get; private set;}
public MyObject(int numColumns)
{
Columns = new string[numColumns];
}
}
但我會嘗試按要求回答這個問題。
您可以執行以下操作:
object ob = ...
object[] ar = ...
for (int i = 0; i < ar.Length; i++)
{
ob.GetType().GetProperty("Column" + i).SetValue(ob, ar[i], null);
}
如果您有抽象基類怎么辦?
public abstract class MyObjectBase
{
public abstract void Initialize(params object[] args);
}
然后您的示例變為:
public class MyObject1 : MyObjectBase
{
public string Column1 { get; set; }
public override void Initialize(params object[] args)
{
this.Column1 = args[0];
}
}
public class MyObject2 : MyObjectBase
{
public string Column1 { get; set; }
public string Column2 { get; set; }
public override void Initialize(params object[] args)
{
this.Column1 = args[0];
this.Column2 = args[1];
}
}
public class MyObject3 : MyObjectBase
{
public string Column1 { get; set; }
public string Column2 { get; set; }
public string Column3 { get; set; }
public override void Initialize(params object[] args)
{
this.Column1 = args[0];
this.Column2 = args[1];
this.Column3 = args[2];
}
}
and so on.....
這樣稱呼:
Array[] ar;
int cnt = ar.Count();
MyObjectBase ob = Activator.CreateInstance(null, "MyObject" + cnt);
ob.Initialize(ar);
嘗試這個...
public interface IMyObject
{
}
public class MyObject1 : IMyObject
{
public string Column1 { get; set; }
}
public class MyObject2 : IMyObject
{
public string Column1 { get; set; }
public string Column2 { get; set; }
}
public class MyObject3 : IMyObject
{
public string Column1 { get; set; }
public string Column2 { get; set; }
public string Column3 { get; set; }
}
接口IMyObject標識您的類。 現在使用反射動態創建...
var assemblyTypes = System.Reflection.Assembly.GetExecutingAssembly().GetTypes();
var instanceList = new List<IMyObject>();
foreach (Type currentType in assemblyTypes)
{
if (currentType.GetInterface("IMyObject") == null)
continue;
Console.WriteLine("Found type: {0}", currentType);
// create instance and add to list
instanceList.Add(Activator.CreateInstance(currentType) as IMyObject);
}
希望這會有所幫助
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.