English 中文(简体)
Can 我将这一职能归入通用名称清单?
原标题:Can I make this function that parses a list of enum names generic?

Non Generic Version (works):

    eTargets ParseTargets(string input)
    {
        eTargets targets = eTargets.None;
        string[] items = input.Split( , );
        foreach (var item in items)
        {
            eTargets target;
            if (Enum.TryParse(item, out target))
            {
                targets |= target;
            }
            else
            {
                Logger.LogError("invalid target: " + item);
            }
        }
        return targets;
    }

Attempt at generic version (does not compile):

    T ParseNames<T>(string delimitedNames) where T : struct
    {
        T result = default(T);
        foreach (var name in delimitedNames.Split( , ))
        {
            T parsed;
            if (Enum.TryParse<T>(name, out parsed)) 
                result |= (int)parsed; // ERROR: cannot convert T to int
                // result |= parsed --> operator |= cannot be applied to T and int
        }
        return (T)result;
    }

如果答案是“否”,那么理解基本限制将是有益的。

问题回答

How about

T ParseNames<T>(string delimitedNames) where T : struct //, Enum
{
    return (T) Enum.Parse(typeof(T), delimitedNames);   
}

你的代码已经意味着1,2,4,8个编号,因此此处唯一的空白是<代码>的要求。

这一工作应当:

static T ParseNames<T>(string delimitedNames) where T : struct
{
    int result = 0;
    foreach (var name in delimitedNames.Split( , ))
    {
        result |= (int)Enum.Parse(typeof(T), name);
    }
    return (T)(object)result;
}




相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签