简体   繁体   中英

C# How can I get the caller member name of the caller?

I'm trying to implement an Enumeration class and I'd like to make the Name field automatically assigned in the constructor of this class.

Here's the working class which I want to improve as well as an example subclass:

public abstract class Enumeration<E> : IComparable where E : Enumeration<E>
{
    public readonly int Id;
    public readonly string Name;

    private static int _count;
    protected Enumeration(string name)
    {
        Id = _count++;

        Name = name;
    }

    // etc
}

public class Color : Enumeration<Color>
{
    public readonly static Color Red = new Color(1, 0, 0);
    public readonly static Color Green = new Color(0, 1, 0);
    public readonly static Color Blue = new Color(0, 0, 1);

    public readonly float R;
    public readonly float G;
    public readonly float B;

    private Color(float r, 
                  float g, 
                  float b,
                  // I wanna move this to super
                  [CallerMemberName]
                  string name="") : base(name)
    {
        R = r;
        G = g;
        B = b;
    }

    // etc
}

So is it possible to accomplish this?

Here is something that would get you the name for free, but you would have to use int type for the RGB values (not really sure why you are using float anyways, they are supposed to be integers):

private Color(int r, int g, int b):base(System.Drawing.Color.FromArgb(r, g, b).Name)
{                        
    R = r;
    G = g;
    B = b;
}

However, it seems like a code smell to me, at least with your current implementation. I am not sure why you want to create this instead of just using the .NET Color type but that is none of my business.

Please note that this will (obviously) break with an ArgumentException if you pass RGBs that don't make sense. Also, make sure to account for unknown colors (this will only work with known ones).

Good luck!

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