碼農學習筆記~C#~使用物件名稱new物件與得到Displayname資訊

By 維尼弘 - 4月 03, 2019



1.使用文字字串,新增物件

使用物件的名稱new出它

var obj = Assembly.Load("組件dll名稱").CreateInstance("class名稱");

簡單說就是使用string 字串,new出物件

EX:
dll名稱(專案名稱):Service_name

namespace Model
{
/// <summary>
/// 環境監控主檔
/// </summary>
internal class ModelData
{
/// <summary>代號</summary>
[DisplayName("代號")]
public string ID { get; set; }
/// <summary>代號1</summary>
[DisplayName("代號")]
public string ID1 { get; set; }
}
}

var obj = Assembly.Load("Service_name").CreateInstance("Model.ModelData");
寫法等於
var obj = new ModelData(); //注意要using Service_name

為啥要這樣做,簡單說就是可以動態的生成相關的物件
進行選擇!!!



2. model 中 得到matadata的資料
(直接對應資料,不用再重新打了!!)

使用
這程式只是單純的將model中有血matadata的資訊存出來,並放入dictionary中
GetDisplayName,取出type中的DisplayName資訊

private object getPropData(string item)
{
var reDict = new Dictionary<string, string>();
var tableObj = Assembly.Load("Service_name").CreateInstance(item);
Type type = tableObj.GetType();
PropertyInfo[] properties = type.GetProperties();
foreach (PropertyInfo info in properties)
{
string temp = GetDisplayName(type, info, true);
if (temp != null)
{
reDict.Add(temp, info.Name);
}
else
{
reDict.Add(info.Name, info.Name);
}
}
return reDict;
}     

private static String GetDisplayName(Type type, PropertyInfo info, bool hasMetaDataAttribute)
{
if (!hasMetaDataAttribute)
{
object[] attributes = info.GetCustomAttributes(typeof(DisplayNameAttribute), false);
if (attributes != null && attributes.Length > 0)
{
var displayName = (DisplayNameAttribute)attributes[0];
return displayName.DisplayName;
}
return info.Name;
}
PropertyDescriptor propDesc = TypeDescriptor.GetProperties(type).Find(info.Name, true);
DisplayNameAttribute displayAttribute =
propDesc.Attributes.OfType<DisplayNameAttribute>().FirstOrDefault();
return displayAttribute != null ? displayAttribute.DisplayName : null;
}

使用方式:
參考上放的資料model

var dictData = getPropData("Model.ModelData");

//dictData 為 {{"代號","ID"},{"代號1","ID1"}}

以上為使用的的東東~~~~歡迎大家提供更好的解法阿!!

  • Share:

You Might Also Like

0 意見