【问题标题】:adding attributes to auto generated code向自动生成的代码添加属性
【发布时间】:2013-09-22 22:45:58
【问题描述】:

我设计了一个数据库,用 sqlmetal 生成了 c# 代码,一切正常。
现在,我正在开发一个 UI,我想为 sqlmetal 创建的类添加一些属性。
阅读此 SO Q&A 后:Can I define properties in partial classes, then mark them with attributes in another partial class? 和此 atrticle:MSDN - MetadataTypeAttribute Class 我尝试了以下操作:

[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; }
    }
}

我检查了 VS 是否在函数 fun 中重新调整了 Book 的属性,但它没有,所以我并不惊讶 DisplayName 属性没有改变。

我做错了什么以及如何解决?

(我使用的是 c#,VS 2010 pro,sqlmetal 生成的代码与 GUI 所在的 .dll 不同)

【问题讨论】:

  • 通过在 UI 中创建 ViewModel 来表示您的实体,您可以省去很多麻烦。他们也会自动允许属性。

标签: c# attributes partial-classes


【解决方案1】:

请注意,在您提到的线程中,其中一个 cmets 说:“这不是 OP 提出的问题的通用解决方案。属性的消费者仍然需要知道寻找元数据类 - 即Attribute.GetCustomAttribute(...) 不会返回这些属性。” 这意味着它不是添加属性的通用解决方案。这是一个解决方案,它要求读取属性的方法理解“MetadataType”,只需转到另一个类以获得其他属性。它不会自动发生。

我知道这不是一个完整的答案,但我建议使用 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);
        }
    }
}

【讨论】:

  • 谢谢。我真的不喜欢这种方法。还有其他方法吗?我不拘泥于属性,我只需要一种简单的方法来自定义表格。
猜你喜欢
  • 2016-08-24
  • 2021-01-06
  • 1970-01-01
  • 2011-08-29
  • 1970-01-01
  • 2010-09-28
  • 1970-01-01
  • 1970-01-01
  • 2014-01-27
相关资源
最近更新 更多