C# 向自动生成的代码添加属性
我设计了一个数据库,用sqlmetal生成了c代码,一切正常C# 向自动生成的代码添加属性,c#,attributes,partial-classes,C#,Attributes,Partial Classes,我设计了一个数据库,用sqlmetal生成了c代码,一切正常 现在,我正在开发一个UI,我想向sqlmetal创建的类添加一些属性。 在阅读了这篇问答文章之后,我尝试了以下方法: [MetadataType(typeof(GUI.metadata.BooksMetaData))] public partial class Book { public void fun() { } } namespace GUI.metadata { public
现在,我正在开发一个UI,我想向sqlmetal创建的类添加一些属性。
在阅读了这篇问答文章之后,我尝试了以下方法:
[MetadataType(typeof(GUI.metadata.BooksMetaData))]
public partial class Book
{
public void fun()
{
}
}
namespace GUI.metadata
{
public class BooksMetaData
{
[DisplayName("hello")]
public object Shelf { get; set; }
}
}
我在函数fun
中检查了VS是否重新确认了Book
的属性,但没有,因此DisplayName
属性没有改变并不奇怪
我做错了什么以及如何修复它
(我使用的是c#,VS 2010 pro,sqlmetal生成的代码与GUI中的代码位于不同的.dll中)请注意,在您提到的线程中,有一条评论说:“对于OP提出的问题,这不是一个通用的解决方案。属性的使用者仍然需要知道如何查找元数据类——也就是说,这些属性不会由Attribute.GetCustomAttribute(…)返回。” 这意味着它不是一个添加属性的通用解决方案。它是一个要求读取属性的方法理解“MetadataType”a的解决方案,它只是转到另一个类以获取其他属性。它不会自动发生 我知道这不是一个完整的答案,但我建议使用Mono.Cecil进行某种后处理,例如:
// pseudo code!
// for every type in assembly...
foreach (var targetType in assembly.Types)
{
// find type which adds attributes to original type
var sourceTypeName = targetType.Name + "Attributes";
var sourceType = assembly.Types.FirstOfDefault(t => t.Name = sourceTypeName);
if (sourceType == null) continue; // no type adding attributes
// for each property in this type...
foreach (var targetProperty in targetType.Properties)
{
// find property which is supposed to have additional attributes
var sourceProperty = sourceType.Properties.FirstOfDefault(
p => p.Name = targetProperty.Name);
if (sourceProperty == null) continue; // no such property
// copy attributes
foreach (var sourceAttribute in sourceProperty.Attributes)
{
targetProperty.Attributes.Add(sourceAttribute);
}
}
}
通过在UI中创建ViewModel来表示实体,您将省去很多麻烦。它们也会自动允许属性。谢谢。我真的不喜欢这种方法。还有其他方法吗?我对属性没有兴趣,我只需要一种简单的方法来自定义表。