简体   繁体   English

C#中的属性编程

[英]Attribute programming in C#

I am new to Attribute programming. 我是属性编程的新手。 Not sure if i am asking the right question or not. 不知道我是否在问正确的问题。

I have an abstract base class (AbstarctBase) and two drived classes Derived1 and Derived2. 我有一个抽象基类(AbstarctBase)和两个驱动类Derived1和Derived2。 My AbstartBase class have two methods Method1 and Method2. 我的AbstartBase类具有两个方法Method1和Method2。

Is it possible to use attribute programming so that when I do this 是否可以使用属性编程,以便在执行此操作时

AbstractBase ab= new Derived1();

I only get access to Method1 and when I use Derived2 class I only get access to Method2 . 我只能访问Method1而当我使用Derived2类时,我只能访问Method2

Is this possible. 这可能吗。 If yes, then can you please give me an example to start with. 如果是,那么请您给我一个例子。

I think you are linking two different concepts of Inhetitance or Polymorphism and Attributes. 我认为您正在将不孕或多态性和属性的两个不同概念联系在一起。 In case of your problem what you can do is you can make an Inerface having a method and implement that differently in your deriving classes than use polymorphism to invoke that implementation that you require. 如果遇到问题,您可以做的是,使Inerface具有一个方法,并在派生类中实现该方法,而不是使用多态性来调用所需的实现。 For example 例如

    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
    }
   }

Where as Attributes in C# are used to attach metadata to your classes or class members, as well as when applying a common behaviour without having to implement a certain interface for each unit that shares the behaviour. C#中的as属性用于将元数据附加到您的类或类成员上,以及在应用通用行为时不必为共享行为的每个单元实现特定接口。 They are used like this 他们这样使用

    [MyAttribute]
    public class MyClass
    {
      //Class body
    }

You need to call the attribute by using GetCustomAttribute() method otherwise it will do nothing. 您需要使用GetCustomAttribute()方法调用该属性,否则它将无效。 For more information on attribute please refer this article http://www.codeproject.com/Articles/2933/Attributes-in-C Hope this hepls you. 有关属性的更多信息,请参考本文http://www.codeproject.com/Articles/2933/Attributes-in-C希望这对您有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM