接口上的C#属性 [英] c# properties on Interface

查看:72
本文介绍了接口上的C#属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请问有人可以帮我把接口或抽象类的属性包括在内是一种最佳做法吗?

Could anyone please help me out whether it's a best practice to include properties on Interface or Abstract Class?

我想接口应该只具有方法签名?

I would imagine an Interface should only have method signatures?

推荐答案

属性是方法的语法糖。考虑一下:

Properties are syntactic sugar for methods. Consider this:

我有一个物业:

String PropertyA { get; set; } 

在运行时,它变成这样:

String get_PropertyA() { ... }
void set_PropertyA(String value) { ... }

请注意, ...表示代码生成器将放置在此处的代码。实际上,我要说的是,属性实际上并不存在于C#之外,因为它们会使用示例中所示的对流编译为方法。为了确认我在说什么,您可以使用反射并查看反射后的代码。

Note that the "..." indicates code that would be put there by the code generator. Effectively what I am saying is that properties don't really exist beyond C#, as they compile down to methods using a convetion indicated in my example. To confirm what I am saying you can use reflection and have a look at what the reflected code looks like.

将属性放在界面(如果他们在实现过程中所做的事情很微不足道)。例如,如果我想设置一个变量并更新其他变量,或者设置一个属性可能由于内部条件而拒绝我的属性分配,那么就不应使用该属性。我认为这是一条适用于接口之外的一般规则。

It can be bad practice however to put properties on an interface if they do something that is non trivial in the implementation. For example, if I want to set a variable and that updates other variables, or setting a property might deny my property assignment because of an internal condition, then a property shouldn't be used. I think that is a general rule that would apply beyond interfaces.

这篇关于接口上的C#属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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