简体   繁体   中英

Action properties

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.

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

eg (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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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