小编Car*_*arl的帖子

C#:使用反射区分记录中的 init 访问器和 set 访问器

我需要使用反射来检查 C# 位置记录中的不可写属性。

这是位置记录示例:

record MyRecord(int MyProperty);
Run Code Online (Sandbox Code Playgroud)

MyProperty正如预期的那样不可写:

MyRecord myRecord = new(5);
Console.WriteLine(myRecord.MyProperty); // 5
//myRecord.MyProperty = 6; <-- yields compile time error as expected
Run Code Online (Sandbox Code Playgroud)

然而,反思告诉我:

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
Run Code Online (Sandbox Code Playgroud)

所以MyProperty看起来是公共可写的。问题似乎是 init 访问器,因为

record MyRecord
{
    public int MyProperty { get; } = 5;
}
Run Code Online (Sandbox Code Playgroud)

CanWrite设置MyPropertyfalse,但这种记录定义不是我需要的。

那么有没有一种方法可以使用反射来区分记录中的 init 访问器和 set 访问器?

c#

5
推荐指数
1
解决办法
360
查看次数

标签 统计

c# ×1