Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modifying Class Attribute on Runtime

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")

Changed to more readable format, thanks to Marc Gravell:

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

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?

Edit:
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).

The designer code is:

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

I want the attribute to be:

[TableAttribute(Name="MyTable")] 

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

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

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

like image 713
Roy Dallal Avatar asked Jan 27 '11 12:01

Roy Dallal


1 Answers

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
    }
}
like image 128
Marc Gravell Avatar answered Nov 14 '22 22:11

Marc Gravell