Is there a way to get the name of an explicit interface property backing field?
For example, for:
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!
}
For property PPPP
I'm looking to figure up the string "_s_backing"
.
I mean. Is there a way to create this helper:
Helpers.DoSomeReflectionMagic( typeof(C), "PPPP" )
// I expect, it returns: `_s_backing`.
What I tried: I was digging into typeof(C)
properties, but I didn't find the backing field anywhere. Maybe there is no way to get it.
The underlying XY problem:
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();
}
}
I would like to do:
var ctx = MyDbContextFactory.NewContext();
var mainCategories = ctx.GetRoots<Category>();