有没有办法获得显式接口属性支持字段的名称?
例如,对于:
public interface I
{
string PPPP { get; }
}
public class C: I
{
private string _other_field = default!; // random private field, just to fill.
public string S => _s_backing; // random property, just to fill.
private string _s_backing = default!;
string I.PPPP => _s_backing; // <--- looking for this one!
}
对于财产
PPPP
我想弄清楚
"_s_backing"
。
我是说。是否有方法创建此帮助程序:
Helpers.DoSomeReflectionMagic( typeof(C), "PPPP" )
// I expect, it returns: `_s_backing`.
我试过的:我在挖掘
typeof(C)
属性,但我在任何地方都找不到支持字段。也许没有办法得到它。
潜在的XY问题:
public interface ITree<T>
{
T? Parent { get; }
IEnumerable<T> Children { get; }
}
public class Category: ITree<Category>
{
public string Name { get; set; }
public Category? MyParentCategory { get; set; }
public IEnumerable<Category> MySubCategories { get; set; }
// Implementing interface
Category? ITree<Category>.Parent => MyParentCategory;;
IEnumerable<Category> ITree<Category>.Children => MySubCategories;
}
// dbcontext with fluent api to configure model blah blah
public static class DbContextTreeExtensions
{
public static IEnumerable<T> GetRoots<T>(this MyDbContext ctx)
{
var backingfieldname = // <-- The Y problem
Helpers
.DoSomeReflectionMagic(typeof(T), "Parent");
return
ctx
.Set<T>()
.Where(q => EF.Property<T?>(q, backingfieldname) == null)
.AsEnumerable();
}
}
我想做:
var ctx = MyDbContextFactory.NewContext();
var mainCategories = ctx.GetRoots<Category>();