我需要使用反射来检查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似乎是公共可写的。问题似乎出在init访问器上,因为
record MyRecord
{
public int MyProperty { get; } = 5;
}将MyProperty的CanWrite设置为false,但这种记录定义不是我需要的。
那么,有没有办法在使用反射的记录中区分init访问器和set访问器呢?
发布于 2021-11-05 11:31:35
您应该在Set方法的ReturnParameter上使用GetRequiredCustomModifiers。您要查找的类型是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);发布于 2021-11-05 11:51:21
如果需要属性MyProperty CanWrite = false,可以通过执行以下操作来实现:
record MyRecord {
public int MyProperty { get; }
public MyRecord(int myProperty) {
MyProperty = myProperty;
}}
如果您查看记录MyRecord(int MyProperty)的IL生成的代码,您将注意到:
public int MyProperty
{
[CompilerGenerated]
get
{
return <MyProperty>k__BackingField;
}
[CompilerGenerated]
init // <- what's being generated
{
<MyProperty>k__BackingField = value;
}
}https://stackoverflow.com/questions/69852464
复制相似问题