在运行时修改类属性 [英] Modifying Class Attribute on Runtime

查看:154
本文介绍了在运行时修改类属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道是否有可能我已经看到:
在运行时更改属性的参数。
我的情况是非常相似,但我试图改变一个类的属性,在运行时:

I am not sure if it is possible I have seen:
Change Attribute's parameter at runtime.
My case is very similar but I am trying to change the attribute of a class in Runtime:

[Category("Change me")]
public class Classic
{
    public string Name { get; set; }
}

答案之一是:

One of the answers was:

Dim prop As PropertyDescriptor = TypeDescriptor
    .GetProperties(GetType(UserInfo))("Age")
Dim att As CategoryAttribute = DirectCast(
     prop.Attributes(GetType(CategoryAttribute)),
     CategoryAttribute)
Dim cat As FieldInfo = att.GetType.GetField(
     "categoryValue",
      BindingFlags.NonPublic Or BindingFlags.Instance)
cat.SetValue(att, "A better description")

更改为更易读的格式,这要感谢马克Gravell:

Changed to more readable format, thanks to Marc Gravell:

TypeDescriptor.AddAttributes(table, new Category{ Name = "Changed" });

使用TypeDescriptor时,但在使用所​​有这些都是好的:

All is good when using TypeDescriptor but when using:

var attrs = (Category[])typeof(Classic).GetCustomAttributes(
    typeof(Category),
    true);
attrs[0].Name

名称具有改变我的文字。
有没有办法来改变运行时该属性?

Name has the "Change me" text.
Is there a way to change this attribute on runtime?

编辑:
我需要这个LINQ2SQL在生成的code的数据库架构设计师。我想使用的用户的默认模式,而不使用XML映射或更改生成code(表仍处于发展阶段,变化频繁)。


I need this for Linq2Sql in the designer the generated code has the DB schema. I want to use the user's default schema without using XML mapping or change the generated code (the table is still in development stage and changes frequently).

设计者code是:

[global::System.Data.Linq.Mapping.TableAttribute(Name="DbSchema.MyTable")]
public partial class MyTable

我想要的属性是:

I want the attribute to be:

[TableAttribute(Name="MyTable")] 

现在我已经挖成的框架code,我认为LINQ2SQL用途:

Now I have dug into the Framework code and I think linq2sql uses:

TableAttribute[] attrs = (TableAttribute[])typeof(MyTable)
   .GetCustomAttributes(typeof(TableAttribute), true);

当我使用TypeDescriptor更改数值不在GetCustomAttributes改变。属性

When I use TypeDescriptor to change the attribute the value isn't changed in GetCustomAttributes.

推荐答案

避免反射的完全的,你可以通过 TypeDescriptor 做到这一点:

Avoiding reflection entirely, you can do this via TypeDescriptor:

using System;
using System.ComponentModel;
using System.Linq;
[Category("nice")]
class Foo {  }
static class Program
{
    static void Main()
    {
        var ca = TypeDescriptor.GetAttributes(typeof(Foo))
              .OfType<CategoryAttribute>().FirstOrDefault();
        Console.WriteLine(ca.Category); // <=== nice
        TypeDescriptor.AddAttributes(typeof(Foo),new CategoryAttribute("naughty"));
        ca = TypeDescriptor.GetAttributes(typeof(Foo))
              .OfType<CategoryAttribute>().FirstOrDefault();
        Console.WriteLine(ca.Category); // <=== naughty
    }
}

这篇关于在运行时修改类属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆