C# c语言中的依赖属性#
这是我的密码C# c语言中的依赖属性#,c#,asp.net,C#,Asp.net,这是我的密码 private MyClass _someProperty [Dependency] public MyClass SomeProperty { get{ if(_someProperty == null) _someProperty = new MyClass() return (MyClass)_someProperty } } 这很好,但我的指导是“不需要为[Dependency]添加“get”
private MyClass _someProperty
[Dependency]
public MyClass SomeProperty
{
get{
if(_someProperty == null)
_someProperty = new MyClass()
return (MyClass)_someProperty
}
}
这很好,但我的指导是“不需要为[Dependency]添加“get”属性”
我不清楚这个[依赖性]属性。当我研究其他代码时,它是这样写的
[Dependency]
public AnotherClass MyNewClass
{
get; set;
}
当我为我的班级尝试上述方法时,它不起作用。如果属性为空,则返回
有人能告诉我[Dependency]的用途是什么,MyClass代码是否有替代方法,以及为什么它会变成“NULL”吗?这与
DependencyAttribute
无关。后一种情况只是自动生成的属性。如果您想使用这种语法,您必须在构造函数中填入值
public class MyClass
{
public MyClass()
{
SomeProperty = new AnotherClass();
}
public AnotherClass SomeProperty { get; set; }
}
请注意,在这种情况下,您不能在getter或setter中执行任何检查。因此,如果需要任何空性检查或希望在setter中引发事件,则必须在自己身上实现getter和setter
public class MyClass
{
private AnotherClass _SomeProperty;
public MyClass()
{
_SomeProperty = new AnotherClass();
}
public AnotherClass SomeProperty
{
get { return _SomeProperty; }
set
{
if(value == null)
throw new ArgumentNullException("SomeProperty");
if(value != _SomeProperty)
{
_SomeProperty = value;
// ToDo: Implement RaiseEvent() and declare event.
RaiseEvent(MyEvent);
}
}
}
}
这是针对Microsoft Unity的,否?[Dependency]告诉Unity,如果从Unity解析属性中包含该属性的类,则还应解析/注入该依赖关系。如果您使用
new
创建一个类,它将无效。@Joachim-在我的例子中,我有[Dependency]属性,但属性为NULL。但我可以在另一个cs文件中获取该属性的实例。例如,在BO中,我得到了实例化的属性,但在DAO中没有。有什么可能?@user2138836在BO中,你从Unity中获得包含属性的对象,而在DAO中你没有?是的,我没有在DAO中获得谢谢。但是我能知道[依赖性]的一般用法吗?可能很简单吧?@user2138836:对不起,我从来没有使用过依赖属性。所以我什么都不能告诉你。