[英]Is there attached property in C# itself?
在C#本身,WPF中是否有类似“附加属性”的东西?
The short answer is no. 最简洁的答案是不。 The slightly longer answer is that this is a bit of an unfortunate story.
稍微长一点的答案是,这是一个不幸的故事。 We designed "extension properties" for C# 4 and got as far as implementing (but not testing) them when we realized, oh, wait, the thing we designed is not really compatible with WPF-style properties.
我们为C#4设计了“扩展属性”,当我们意识到,哦,等等,我们设计的东西与WPF风格的属性并不真正兼容时,就实现了(但没有测试)它们。 Rather than redesign and reimplement the feature we ended up cutting it.
我们最终削减了它,而不是重新设计和重新实现该功能。
The even longer version is here: 更长的版本在这里:
http://blogs.msdn.com/b/ericlippert/archive/2009/10/05/why-no-extension-properties.aspx http://blogs.msdn.com/b/ericlippert/archive/2009/10/05/why-no-extension-properties.aspx
AttachedProperties是.NET Framework的一部分,不是C#语言规范的一部分,特别是System.Activities.Presentation.Model命名空间的一部分,它是WPF特定的。
In WPF, an attached property allows you to do something like: 在WPF中,附加属性允许您执行以下操作:
<TextBlock Grid.Row="2" Text="I know nothing about grids!" />
This would be like having a class in C# defined as: 这就像将C#中的类定义为:
public class TextBlock
{
public string Text { get; set; }
}
And being able to do this: 能够做到这一点:
var tb = new TextBlock();
tb.Grid.Row = 2; // this line would not compile
In order to make this work, you'd need to pass a Grid
object into your TextBlock class: 为了使这项工作,您需要将
Grid
对象传递到TextBlock类:
public class TextBlock
{
public string Text { get; set; }
public Grid Grid { get; set; }
public TextBlock(Grid grid)
{
Grid = grid;
}
}
But I don't think there's anything directly equivalent to the way attached properties work in WPF. 但我认为没有任何东西直接等同于附加属性在WPF中的工作方式。 You'd need to build it by hand.
你需要手工制作它。
What are you trying to accomplish? 你想达到什么目的?
You can use the ConditionalWeakTable<TKey, TValue>
class to attach arbitrary state to an instance. 您可以使用
ConditionalWeakTable<TKey, TValue>
类将任意状态附加到实例。 You can combine it with extension methods to create a form of extension properties , but unfortunately without using the nice property syntax in C#. 您可以将它与扩展方法结合使用以创建扩展属性的形式,但遗憾的是没有在C#中使用nice属性语法。
I think you're thinking of getters and setters. 我想你在考虑吸气剂和制定者。
They are created like this: 它们是这样创建的:
public class Person
{
//default constructor
public Person()
{
}
private string _Name;
public string Name
{
//set the person name
set { this._Name = value; }
//get the person name
get { return this._Name; }
}
}
More on how they work here: http://msdn.microsoft.com/en-us/library/aa287786(v=vs.71).aspx 有关它们如何在这里工作的更多信息: http : //msdn.microsoft.com/en-us/library/aa287786(v = vs.71).aspx
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.