I have a question wheater or not it is possible (and if it is, how) to access class
members from inside a Func<T, TResult>
delegate.
For example, I have the following class
:
class NinjaTurtle
{
public string Sound { get; set; }
public Func<string, string> DoNinjaMove { get; set; }
}
Now I'd like to do this
NinjaTurtle leonardo = new NinjaTurtle();
leonardo.Sound = "swiishhh!";
leonardo.DoNinjaMove = (move) => {
if(move == "katana slash") return leonardo.Sound;
return "zirp zirp zirp";
}
The problem is, how do I correctly access the property Sound
, when I define the callback function? Is it OK to just use the reference to the instance from outside the function? Would this still work when I pass the object to another method, or even when this would be part of a dll, and I would return the object leonardo from a function in the dll? Would it "survive" serialization / deserialization?
(Thanks Vladimir and Lee, the question is now more specific to what I would like to know).
DoNinjaMove
should be aFunc<string, string>
. – Jonijonie