在c#中将类成员引用为枚举

本文关键字:引用 枚举 成员 | 更新日期: 2023-09-27 18:06:25

是否有方法将类'成员'传递为一等值?

public class Bike {
    public Color BikeColour { get; set; }
    public bool  IsGirlsBike { get; set; }
}

我想引用字段名,而不需要任何对象的概念。

我想我想要的是类似enum的东西:

public enum BikeFields {BikeColour, IsGirlsBike};

但没有明确定义

在c#中有办法做到这一点吗?

编辑:很抱歉说得这么模糊;我希望能够将类成员引用为第一类事物(几乎像绑定类型)。

Set<Bike:T> whichFieldsHaveBeenDrawn = new Set<Bike:T>();

自行车:T是未定义的,我希望下面的插图能清楚地说明这种新类型是如何工作的。

whichFieldsHaveBeenDrawn.Include(Bike.BikeColour);
var remainingFields = Set.Subtract(Bike.GetAllFields(), whichFieldsHaveBeenDrawn);
Bike b = new Bike();
foreach (var field in remainingFields) { Draw(field, b); }

我想我可以用反射做到这一点,但我希望他们在编译时合格…

在c#中将类成员引用为枚举

不能与类同时拥有静态类型Enum,因为它们是在同一步骤中编译的。所以你需要两个步骤,第一个是拥有类,然后生成相应的Enum。两步实现这一目标的一种方法是使用t4模板,像这样:

1。创建一个类库(假设称为ClassLibrary)。这将包含您的Bike类。

2。在控制台应用程序(或任何其他类型的项目,你可能需要)添加一个t4文本模板,像这样:

<#@ template debug="true" hostspecific="false" language="C#" #>
<#@ assembly name="$(TargetDir)'ClassLibrary.dll" #>
<#@ assembly name="System.Core" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Text" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ import namespace="ClassLibrary" #>
<#@ output extension=".generated.cs" #>
namespace SO_31801914
{
<#
    var classes = new Type[] { typeof(ClassLibrary.Bike) };
    foreach (var cls in classes)
    {
#>
    public enum <#=cls.Name#>Enum
    {
<#      var props = cls.GetProperties();        
        for (int i = 0 ; i < props.Length; i++)
        {
            var prop = props[i];
            bool skipComma = false;
            if (i == props.Length - 1)
            {
                skipComma = true;
            }
#>
            <#=prop.Name#><#=skipComma ? string.Empty : ","#>
<#
        }
#>
    }
<#
    }
#>
}

结果将是:

namespace SO_31801914
{
    public enum BikeEnum
    {
        BikeColour,
        IsGirlsBike
    }
}

构建ClassLibrary然后右键单击模板并单击"运行自定义工具"。在TemplateName.generated.cs中,您将得到上述结果。

只是把它放在那里。但是如果你想直接引用成员的名字…为什么不用nameof呢?

class Foo
{
    public int A { get; set; }
    public int B { get; set; }
}
class Program
{
    static void Main(string[] args)
    {
        var rendered = new List<string>();
        if (!rendered.Contains(nameof(Foo.A)))
        {
            //Do something
            rendered.Add(nameof(Foo.A));
        }
    }
}

如果你真的需要一个enum:

public enum FooFields
{
    A,
    B
}
var enumA = Enum.Parse(typeof (FooFields), nameof(Foo.A));

您可以将属性和它们的值转换为字典

var bike = new Bike() { BikeColour = Color.Red, IsGirlsBike = true };
var props = bike.GetType().GetProperties()
           .ToDictionary(p => p.Name, p => p.GetValue(bike, null));

编辑

如果我没理解错的话,你是想写这样的代码

var props = GetAllProperties<Bike>()
            .Except(new[] { GetProperty<Bike>(x => x.BikeColour) });
Draw(bike, props);

public IEnumerable<PropertyInfo> GetAllProperties<T>()
{
    return typeof(T).GetProperties();
}
public PropertyInfo GetProperty<T>(Expression<Func<T,object>> expr)
{
    var uExpr = expr.Body as UnaryExpression;
    var memberExpr = uExpr.Operand as MemberExpression;
    return memberExpr.Member as PropertyInfo;
}
public Dictionary<string,object> GetValues<T>(T obj, IEnumerable<PropertyInfo> props)
{
    return props.ToDictionary(p => p.Name, p => p.GetValue(obj, null));
}
void Draw(Bike b, IEnumerable<PropertyInfo> properties)
{
    var values = GetValues(b, properties);
}