我需要使用反射来检查 C# 位置记录中的不可写属性。
这是一个示例位置记录:
record MyRecord(int MyProperty);
MyProperty
如预期的那样是不可写的:
MyRecord myRecord = new(5);
Console.WriteLine(myRecord.MyProperty); // 5
//myRecord.MyProperty = 6; <-- yields compile time error as expected
然而,反射告诉我:
PropertyInfo pi = typeof(MyRecord).GetProperty("MyProperty");
Console.WriteLine(pi.CanWrite); // True
MethodInfo mi = pi.GetSetMethod();
Console.WriteLine(mi == null); // False
Console.WriteLine(mi.IsPublic); // True
所以 MyProperty
似乎是公共(public)可写的。问题似乎是 init 访问器,因为
record MyRecord
{
public int MyProperty { get; } = 5;
}
已将 MyProperty
的 CanWrite
设置为 false
,但这种记录定义不是我需要的。
那么有没有办法使用反射来区分记录中的 init 访问器和 set 访问器?
最佳答案
你应该使用 GetRequiredCustomModifiers
在 Set
方法的 ReturnParameter
上。您要查找的类型是 IsExternalInit
var rec = typeof(MyRecord);
var prop = rec.GetProperty("MyProperty");
var setMethod = prop.GetSetMethod();
var mods = setMethod.ReturnParameter.GetRequiredCustomModifiers().Contains(typeof(IsExternalInit));
Console.WriteLine("Init: {0}", mods);
关于C#:使用反射区分记录中的 init 访问器和 set 访问器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69852464/