Action properties

怎甘沉沦 提交于 2019-12-08 06:05:32

问题


Can anybody explain me this code extract.

public abstract Action<int> serialpacket { set; get; }

I am a bit confused about it. I know roughly what it does but it would be better if somebody can shed a bit light on it.


回答1:


serialpacket is an abstract property that, when implemented, will return a method reference or lamda that takes an integer parameter and returns nothing.

e.g (ignoring the setter).

public override Action<int> serialpacket
{
    get { return i => Console.WriteLine(i); }
    set { ... }
}

or

public void Trousers(int i)
{
   Console.WriteLine(i);
}

public Action<int> serialpacket
{
    get { return Trousers; }
    set { ... }
}

One could then use serialpacket thusly:

serialpacket(10);

As it is a property with a setter, one could also do:

public override Action<int> serialpacket { get; set; }

serialpacket = Trousers;
serialpacket(10);
// prints 10 to the console

With the same definition of Trousers as above.




回答2:


Encapsulates a method that has a single parameter and does not return a value.

http://msdn.microsoft.com/en-us/library/018hxwa8.aspx

EDIT: In your example, it is a property to which you can assign (in a derived class - because it is abstract) a delegate that takes an int and does not return a value.




回答3:


This is a property of type Action<int>. Action<int> is a function that takes int parameter and doesn't return a value.

You can use it as follows:

instance.serialpacket(42);

The property is abstract - it must be overridden in a concrete derived class.

It is a bit bizarre to have an abstract property with a public setter. What would probably be better is a read-only property:

public abstract Action<int> serialpacket { get; }

Otherwise, if the property can be set publicly, than a non-abstract version will be enough

public Action<int> serialpacket { get; set; }

You can also limit the setter to derived classes:

public Action<int> serialpacket { get; protected set; }


来源:https://stackoverflow.com/questions/15138195/action-properties

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!