0

I have trouble using System.Func.

public Func<int> OnCreated=new Func<int>(int ASD){ Debug.Log (ASD); };

Is this the proper way to use it? I want to make a dynamic function that can be called. Also can the System.Func be serialized via XML?

m0skit0
  • 25,268
  • 11
  • 79
  • 127

2 Answers2

2

Maybe you're looking for Action<> instead?

Action<int> myAction = myIntParam => Debug.Log(myIntParam);
myAction(myInteger);

If you want to take an input parameter, and return something, you should use Func<>

Func<int, int> myFunc = myIntParam => {
   Debug.Log(myIntParam);
   return 5;
};
int five = myFunc(myInteger);

Also, if you want to serialize/deserialize, you need to take it one step further. Namely, by def Func does not really have any meaningful information for it to be serialized, you should wrap it in Expression. You can get started by googling for "C# serialize expression", eg: https://expressiontree.codeplex.com

Erti-Chris Eelmaa
  • 25,338
  • 6
  • 61
  • 78
0

Just like any other thing in .NET Func is an Object. Func is an object of type Delegate.You can serialize/deserialize any serializable object. Func returns a value and can take up to 16 parameters.

The way you would use it is like this :

Func<int> w = new Func<int>(() => { return 1; });

You should first be familiar with the use of delegates. Check this : when & why to use delegates?

P.S Serializing delegates is a risky thing to do since they are pointers to functions that are inside your program.|

You can check how you can do the serialization over here : Could we save delegates in a file (C#)

Community
  • 1
  • 1
Christo S. Christov
  • 2,268
  • 3
  • 32
  • 57
  • "You can serialize/deserialize any object." -- No, you can't. You can only serialize/deserialize serializable objects, and which objects are serializable depends on the type of serialization that's done. –  Mar 21 '15 at 14:17
  • So can I serialize Functions/Actions? If no, is there a way to serialize them without XML? – Tire Fruck Mar 21 '15 at 14:31
  • @TireFruck Yes, you absolutely can do that but that's not really something you want to do in your free time. – Christo S. Christov Mar 21 '15 at 14:32