简体   繁体   中英

C#: Convert a generic function to a Func object

I have the following function:

private int GetEnumTypeUnderlyingId<T>()
        {
            return (int)Enum.Parse(typeof(T), Enum.GetName(typeof(T), _franchise.LogonDialog));
        }

I want to convert it to a Func type . I write something like:

Func<int> GetEnumTypeUnderlyingIdFunc<T> = () => (int)Enum.Parse(typeof(T), Enum.GetName(typeof(T), _franchise.LogonDialog));

But this does not work. I am not really comfortable when working with Func<>, Generics and lambda expressions so any help will be greatly appreciated

You can define your own delegate. Here is what you are looking for:

//Your function type
delegate int GetEnumTypeUnderlyingIdFunc<T>();

//An instance of your function type
GetEnumTypeUnderlyingIdFunc<int> myFunction = () => //some code to return an int ;

Also this works too.

//An instance of Func delegate
Func<int> GetEnumTypeUnderlyingIdFunc = () => //some code to return an int;

Another solution would be

public Func<int> GetTheFunc<T>(T val)
{
    Func<int> func = () => (int)Enum.Parse(typeof(T),Enum.GetName(typeof(T),val));
    return func;
}

Then

var func = GetTheFunc<_franchise>(_franchise.LoginDialog);

//Now you can use the func, pass it around or whatever..
var intValue = func();

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