简体   繁体   English

如何提供动态属性?

[英]How to provide a dynamic property?

I am using a class with a string property on it. 我正在使用带有字符串属性的类。 I am looking for some sort of event notification when somebody reads the value of this property, so that I can provide the property dynamically. 当有人读取此属性的值时,我正在寻找某种事件通知,以便可以动态提供该属性。 For example, usually somebody would do: 例如,通常有人会这样做:

string foo = someClass.Property;

And it returns whatever string value is currently assigned to Property. 它返回当前分配给Property的任何字符串值。

However, I want to say something like: 但是,我想说些类似的话:

someClass.PropertyRead += new EventHandler<PropertyReadEventArgs>("Property", Property_Read);

private void Property_Read(object sender, PropertyReadEventArgs e)
{
    e.Value = "some dynamically generated string here.";
}

Any idea if something like this is possible? 知道这样的事情是否可行吗?

Why not use plain property getter? 为什么不使用普通属性获取器?

public string Property {
    get { return Generate(); }
}

If you'd rather inject the strategy you can do: 如果您愿意注入策略,则可以执行以下操作:

public Func<string> PropertyGetter{ get; set; }

public string Property{ 
   get{
       return PropertyGetter();
      }
}

And then 接着

myclass.PropertyGetter = Console.ReadLine;

If you are using a Property then you are probably using a getter in which you can create your dynamic string. 如果使用的是Property,则可能使用的是getter,可以在其中创建动态字符串。

public String SomeProperty
{

get
 {
    return DynamicString();
 }

}

private String DynamicString()
{
   return "some dynamically generated string here.";
}

It sounds like you want to add properties at runtime, and do so without using a special syntax to access them. 听起来您想在运行时添加属性,而无需使用特殊语法来访问它们就可以这样做。

So myClass.Property does not exist at compile time. 因此,myClass.Property在编译时不存在。

My (guess) is you would need to create a dynamic proxy for your object so you can intercept the calls and provide implementations for missing properties. 我的猜测是,您需要为对象创建一个动态代理,以便可以拦截调用并提供缺少属性的实现。

I'm not sure about .NET 4.0 and whether it makes this easier or not. 我不确定.NET 4.0以及它是否使此操作更容易。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM