Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

UnsafeAccessor #455

Open
ufcpp opened this issue Oct 17, 2023 · 0 comments
Open

UnsafeAccessor #455

ufcpp opened this issue Oct 17, 2023 · 0 comments
Labels

Comments

@ufcpp
Copy link
Owner

ufcpp commented Oct 17, 2023

ブログにでも書く?
C# 入門の雑記?

using System.Runtime.CompilerServices;

var p = new Private();
GetValue(p) = 99;
Console.WriteLine(p); // 99

// アクセス制限無視してメンバーにアクセスする手段を用意したらしい。
// 今まではリフレクション(IL Emit)でやりたい放題やってたけども、
// AOT (リフレクションをソースジェネレーターで置き換えたい)で困るからって。
//
// ランタイム側で UnsafeAccessor 属性付きの external メソッドを特別扱い(intrinsic)してる。
[UnsafeAccessor(UnsafeAccessorKind.Field, Name = "_value")]
extern static ref int GetValue(Private x);

class Private
{
    private int _value; // Make field readonly 出っぱなしにはなる。

    public override string ToString() => _value.ToString();
}

基本的には AOT 向け。
シリアライザーで使うのが一番の動機。

単体テストとかにも使えそう。 → すでに neue さんが
InternalVisibleTo は広範囲にわたって公開されすぎる感ある。
Visual Studio は昔 internal accessor (中身はリフレクション)とか生成してくれる機能持ってたのに気が付いたら消えてた。

@ufcpp ufcpp added the C# 12.0 label Oct 17, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant