![](/img/trans.png)
[英]How can I capture the name of a C# static string resource property without changing the caller?
[英]C# How can I get the caller member name of the caller?
我正在尝试实现一个枚举类,我想让Name
字段在这个类的构造函数中自动分配。
这是我想要改进的工人阶级以及一个示例子类:
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
}
那么有没有可能做到这一点呢?
这里有一些可以免费为您提供名称的东西,但是您必须对 RGB 值使用int
类型(不太确定您为什么要使用浮点数,它们应该是整数):
private Color(int r, int g, int b):base(System.Drawing.Color.FromArgb(r, g, b).Name)
{
R = r;
G = g;
B = b;
}
但是,对我来说,这似乎是一种代码味道,至少在您当前的实现中是这样。 我不确定为什么要创建它而不是仅使用 .NET Color
类型,但这与我无关。
请注意,如果您传递没有意义的 RGB,这将(显然)与ArgumentException
中断。 此外,请确保考虑未知颜色(这只适用于已知颜色)。
祝你好运!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.