如何使用反射来更改c#中不存在的字段?

问题描述 投票:0回答:2

我有下面的代码块,它应该打印 404,而不使用不安全代码或对 Mutate 方法进行任何更改

const string constStr = "000";
Mutate(constStr);
var nonConst = "000";
Console.WriteLine(nonConst);  

static void Mutate(string str)
{
    
}
c# .net reflection
2个回答
1
投票

您无法更改不存在的字段,但可以打印 404:

const string constStr = "000";
Mutate(constStr);
var nonConst = "000";
Console.WriteLine(nonConst);  

static void Mutate(string str)
{
    Console.SetOut(new Foo(Console.Out));
}

class Foo(TextWriter o) : TextWriter
{
    public override Encoding Encoding => Encoding.UTF8;
    public override void WriteLine(string? value) => o.WriteLine("404");
}

0
投票

编译为 X86 项目时将输出

"404"
。 (注意:对于 x64 或 AnyCPU 版本,它将输出“
004
”):

using System;
using System.Runtime.InteropServices;

namespace Console1;

public static class Program
{
    public static void Main()
    {
        const string constStr = "000";
        var nonConst = "000";
        Mutate(constStr);
        Console.WriteLine(nonConst);
    }

    static void Mutate(string s)
    {
        var nasty = new StringToChar { str = s };
        char[] ch = nasty.chr!;

        ch[0] = '4';
        ch[1] = '0';
        ch[2] = '4';
    }
}

[StructLayout(LayoutKind.Explicit)]
public struct StringToChar
{
    [FieldOffset(0)] public char[] chr;
    [FieldOffset(0)] public string str;
}

是的,这很糟糕。永远不要这样做!

© www.soinside.com 2019 - 2024. All rights reserved.