C#中的属性编程
本文关键字:编程 属性 | 更新日期: 2023-09-27 17:59:39
我是属性编程的新手。不确定我问的问题是否正确。
我有一个抽象基类(AbstractBase)和两个驱动类Derived1和Derived2。我的AbsartBase类有两个方法Method1和Method2。
有没有可能使用属性编程,这样当我做这个时
AbstractBase ab= new Derived1();
我只能访问Method1
,当我使用Derived2
类时,我只能访问Method2
。
这可能吗。如果是,那么你能给我举个例子吗。
我认为您正在将固有性或多态性和属性这两个不同的概念联系起来。在您遇到问题的情况下,您可以做的是使Inerface具有一个方法,并在派生类中实现该方法,而不是使用多态性来调用所需的实现。例如
public interface IBase
{
void Foo();
}
public class Derived1: IBase
{
public void Foo()
{
//Print Derived 1
}
}
public class Derived2: IBase
{
public void Foo()
{
//Print Derived 2
}
}
public class Program
{
public static void Main(String args[])
{
IBase base=new Derived1();
base.Foo();//This prints Derived 1
base=new Derived2();
base.Foo();//This prints Derived 2
}
}
C#中的Where as Attributes用于将元数据附加到类或类成员,以及在应用公共行为时,而不必为共享行为的每个单元实现特定接口。它们像这个一样使用
[MyAttribute]
public class MyClass
{
//Class body
}
您需要使用GetCustomAttribute()方法调用该属性,否则它将不起任何作用。有关属性的更多信息,请参阅本文http://www.codeproject.com/Articles/2933/Attributes-in-C希望这能帮你。