我的接口IResourcePolicy
包含属性Version
。我必须实现这个包含值的属性,代码写在其他页面中:
IResourcePolicy irp(instantiated interface)
irp.WrmVersion = "10.4";
如何实现属性version
?
public interface IResourcePolicy
{
string Version
{
get;
set;
}
}
答案 0 :(得分:261)
在界面中,指定属性:
public interface IResourcePolicy
{
string Version { get; set; }
}
在实现类中,您需要实现它:
public class ResourcePolicy : IResourcePolicy
{
public string Version { get; set; }
}
这看起来很相似,但它完全不同。在界面中,没有代码。您只需指定存在具有getter和setter的属性,无论它们将执行什么操作。
在课堂上,你实际上是在实施它们。最简单的方法是使用此{ get; set; }
语法。编译器将创建一个字段并为其生成getter和setter实现。
答案 1 :(得分:21)
你的意思是这样吗?
class MyResourcePolicy : IResourcePolicy {
private string version;
public string Version {
get {
return this.version;
}
set {
this.version = value;
}
}
}
答案 2 :(得分:14)
接口不能包含任何实现(包括默认值)。你需要切换到抽象类。
答案 3 :(得分:1)
在界面中使用属性的简单示例:
using System;
interface IName
{
string Name { get; set; }
}
class Employee : IName
{
public string Name { get; set; }
}
class Company : IName
{
private string _company { get; set; }
public string Name
{
get
{
return _company;
}
set
{
_company = value;
}
}
}
class Client
{
static void Main(string[] args)
{
IName e = new Employee();
e.Name = "Tim Bridges";
IName c = new Company();
c.Name = "Inforsoft";
Console.WriteLine("{0} from {1}.", e.Name, c.Name);
Console.ReadKey();
}
}
/*output:
Tim Bridges from Inforsoft.
*/
答案 4 :(得分:0)
J.Random Coder的答案并初始化版本字段。
private string version = "10.4';
答案 5 :(得分:0)
您应该使用抽象类来初始化属性。您不能在Inteface中初始化。