C# .NET 8 Reflection is failing to set property when application is published - Stack Overflow

admin2025-04-17  3

The code shown below works in .NET 4.6.2, and it works in DEBUG mode for .NET 8.

The code however FAILS after this it is published as a single file and when I try to run it.

I'm using reflection to set a private value, it's not really a big deal. The exception is

Property set method not found

Code:

/// <summary>
/// This gets called at startup. The point of this is to prevent us from
/// making everything a const with [General.Yes = "General.Yes"]. Saves a step in
/// development that was getting annoying.
/// </summary>
public static void SetupKeys()
{
    var thisNamespace = typeof( TranslationKeys ).Namespace;
    var thisName = nameof( TranslationKeys );
    var fullNameStart = string.Concat( thisNamespace, ".", thisName, "+" );

    var classes = Assembly.GetExecutingAssembly()
            .GetTypes()
            .Where( t => t.IsClass && t.IsNested && t.FullName != null && t.FullName.StartsWith( fullNameStart ) );

    foreach (var c in classes)
    {
        var className = c.Name;
        var props = c.GetProperties();

        foreach (var p in props)
        {
            var propName = p.Name;
            p.SetValue(null, string.Concat(className, ".", propName), BindingFlags.NonPublic, );
        }
    }
}

/// <summary>
/// Things that we will use all over the place.
/// </summary>
public static class General
{
    public static string Yes { get; private set; } = string.Empty;
}

I'm just stumped on this one. Since the issue occurs after packaging, the only thing I can do right now is add some log statements, but we know the error is "Property set method not found", and we know what that means. So... now what?

转载请注明原文地址:http://anycun.com/QandA/1744852850a88532.html