[英]How to add a property to an existing class programmatically?
我想添加另一個屬性public int ID { get; set; }
public int ID { get; set; }
public int ID { get; set; }
使用 C# 到下面的 class。 不知道T4旁邊有沒有辦法或者部分class。 CodeDom 怎么樣? 我不熟悉它。 請幫我一個忙,謝謝!
public class DgItem
{
public string Name { get; set; }
}
您為您的財產創建一個字段
CodeMemberField cmf = new CodeMemberField(new CodeTypeReference(type), name);
cmf.Attributes = attr;
cmf.InitExpression = new CodePrimitiveExpression(value);
你創建你的財產
CodeMemberProperty cmp = new CodeMemberProperty()
{
Name = name,
Type = new CodeTypeReference(type),
Attributes = attr,
};
然后添加 get 和 set 語句
cmp.GetStatements.Add(new CodeMethodReturnStatement(new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), field.Name)));
cmp.SetStatements.Add(new CodeAssignStatement(new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), field.Name), new CodePropertySetValueReferenceExpression()));
這應該可以解決問題
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.