标签: system.reflection

为什么通过反射更改静态只读字段后,该只读字段的输出是旧的?

为什么只读变量“someValue”(但我们仍然可以通过反射更改其值)输出为“10”,尽管它实际上确实更改为 55?

static class Program
{
    static readonly int someValue = 10;

    static void Main(string[] args)
    {
        Console.WriteLine(someValue); // 10

        typeof(Program)
             .GetField("someValue", BindingFlags.Static | BindingFlags.NonPublic)
             .SetValue(null, 55); // change readonly field via reflection to 55

        Console.WriteLine(someValue); // output in console 10, 
                                      // but in visual studio debugger it shows 55

        Console.ReadKey();
    }
}
Run Code Online (Sandbox Code Playgroud)

.net c# jit inlining system.reflection

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

在实现具有默认方法实现的接口的类上使用“GetMethod”返回 null

我有几个接口(IMapFromIMapTo),可以让我简化AutoMapper配置。每个接口都有MapToMapFrom方法的默认实现。我有一个单独的MappingProfile类,它使用反射来查找所有实现类,并调用它们的映射创建。

上述类看起来像这样:

public interface IMapFrom<T>
{
    void MapFrom(Profile profile) => profile.CreateMap(typeof(T), GetType());
}

public interface IMapTo<T>
{
    void MapTo(Profile profile) => profile.CreateMap(GetType(), typeof(T));
}

public class MappingProfile : Profile
{
    public MappingProfile()
    {
        ApplyMappingsFromAssembly(Assembly.GetExecutingAssembly());
    }

    private void ApplyMappingsFromAssembly(Assembly assembly)
    {
        var types = assembly.GetExportedTypes()
            .Where(t => t.GetInterfaces().Any(i =>
                i.IsGenericType && (i.GetGenericTypeDefinition() == typeof(IMapFrom<>) || 
                                    i.GetGenericTypeDefinition() == typeof(IMapTo<>))))
            .ToList();

        foreach (var type in types)
        {
            var instance = Activator.CreateInstance(type); …
Run Code Online (Sandbox Code Playgroud)

c# reflection system.reflection c#-8.0 default-interface-member

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

从 Assembly.ReflectionOnlyLoad 迁移到 MetadataLoadContext

我有以下代码适用于 .NET 4.8 类库,它使用Assembly.ReflectionOnlyLoad

代码:

// Retrieve the doman assembly used by the compilation
Assembly baseAssembly = typeof(MyType).Assembly;

// Retrieve the location of the assembly and the referenced assemblies used by the domain
AssemblyName[] baseAssemblyReferences = baseAssembly.GetReferencedAssemblies();
List<string> baseAssemblyLocations = baseAssemblyReferences.Select(a => Assembly.ReflectionOnlyLoad(a.FullName).Location).ToList();
baseAssemblyLocations.Add(baseAssembly.Location);

// Create Compilation Parameters
CompilerParameters compileParams = new CompilerParameters()
{
    CompilerOptions = Constants.Assembly.CompileToLibrary,
    GenerateInMemory = true
};
compileParams.ReferencedAssemblies.AddRange(baseAssemblyLocations.ToArray());

// Create Code Provider
CSharpCodeProvider provider = new CSharpCodeProvider(new Dictionary<string, string>() {
        { Constants.Assembly.CompilerVersion, Constants.Assembly.CompilerVersion4 }
    }); …
Run Code Online (Sandbox Code Playgroud)

c# system.reflection .net-6.0 metadataloadcontext

5
推荐指数
0
解决办法
333
查看次数

使用反射将值写入struct var成员不起作用,但它适用于类

我一直在这里阅读stackoverflow如何使用反射写入类var成员.我使用类似的东西:

typeof(MyClass).GetField("myvar", BindingFlags.Public | BindingFlags.Instance).SetValue(instancie, 10);
Run Code Online (Sandbox Code Playgroud)

这适用于类,但如果我在读取myvar时对Struct而不是类执行相同操作,我总是得到0(int的默认构造值).这是我使用的代码:

struct MyStruct
{
    public int myvar;
}

MyStruct instance=new MyStruct();

typeof(MyStruct).GetField("myvar", BindingFlags.Public | BindingFlags. BindingFlags.Instance).SetValue(instance, 10);
Run Code Online (Sandbox Code Playgroud)

有谁知道为什么这可能是hapenning?

c# reflection system.reflection

4
推荐指数
1
解决办法
206
查看次数

Assembly.Load性能影响

我正在开发一个组件,它执行使用ioc注册的任何接口的临时方法,执行时刻取决于不同的触发器.它必须能够保存要对数据库执行的操作,因此我将方法名称,类型和参数列表(序列化为BLOB)保存到数据库中,直到需要为止.

当触发发生时,我需要在类型的实例上执行方法.因为我正在使用依赖注入,我将接口名称保存到数据库中(格式"Namespace.IInterface, AssemblyName")

Resolve<IInterface>()在ioc容器上运行方法,我需要它的实例Type:

Assembly assembly = System.Reflection.Assembly.Load(assemblyName);
Type service = assembly.GetType(typeName);
object instance = IOCContainer.Resolve(service);
Run Code Online (Sandbox Code Playgroud)

我的问题是:

  • 如果我确定包含程序集已经加载到应用程序域中,是否有更好的方法从其名称获取Type实例?(我试过简单Type.Load(typeName)但得到了null)
  • 如果已加载有问题的程序集,CLR会优化该进程(使用已加载),还是需要手动缓存程序集列表以防止反复加载同一程序集的性能影响?

c# clr performance system.reflection .net-assembly

4
推荐指数
1
解决办法
3017
查看次数

从IEnumerable <Dictionary <string,object >>获取键和值

我有一个 IEnumerable < Dictionary < string, object > > 对象.

我想在数组中得到"aaavalue""bbbvalue""cccvalue""dddvalue".

样本数据:

IEnumerable<Dictionary<string, object>> testData = new IEnumerable<Dictionary<string, object>>();

/* Values in testData will be like
   [0] - 
         aaa - aaaValue   (Key, Value)
         bbb - bbbValue
         ccc - cccValue
         ddd - dddValue  
   [1] - 
         aaa - aaaValue   (Key, Value)
         bbb - bbbValue
         ccc - cccValue
         ddd - dddValue  

    and so on */
Run Code Online (Sandbox Code Playgroud)

我知道可以使用Reflection或LINQ.但我无法弥补.

请帮忙..

回答:

IEnumerable<Dictionary<string, object>> enumerable = testData as List<Dictionary<string, object>> ?? testData .ToList();
foreach (Dictionary<string, object> objects in enumerable) …
Run Code Online (Sandbox Code Playgroud)

c# linq dictionary .net-4.0 system.reflection

4
推荐指数
1
解决办法
1万
查看次数

用F#语言覆盖C#类中的方法会使该方法无法内省吗?

我有以下C#类:

public class Foo {
    protected virtual void Bar (){
    }
}

public class Baz : Foo {
    protected override void Bar (){
    }
}
Run Code Online (Sandbox Code Playgroud)

如果我反省它们,方法Bar总是在那里:

[<EntryPoint>]
let main args =
    let methodFromFoo = typedefof<Foo>.GetMethod("Bar", BindingFlags.Instance ||| BindingFlags.NonPublic)
    if (methodFromFoo <> null) then
        Console.WriteLine ("methodFromFoo is not null")
    else
        Console.WriteLine ("methodFromFoo is null")

    let methodFromBaz = typedefof<Baz>.GetMethod("Bar", BindingFlags.Instance ||| BindingFlags.NonPublic)
    if (methodFromBaz <> null) then
        Console.WriteLine ("methodFromBaz is not null")
    else
        Console.WriteLine ("methodFromBaz is null")
Run Code Online (Sandbox Code Playgroud)

结果是这is not null两种情况. …

c# reflection f# system.reflection c#-to-f#

4
推荐指数
1
解决办法
383
查看次数

System.Reflection.TargetException有什么作用:非静态方法需要一个目标。意思?

在我的应用程序中,我从某个地方收到functionCode值,并且需要反映相应的类。我试图根据 解决方案反映适当的类型。但这对我不起作用。我无法使用GetField()方法,因为我正在处理PCL项目。因此,我尝试了以下代码行:

AssemblyName name = new AssemblyName("MyLibrary");
var type = Assembly.Load(name);
type.DefinedTypes.FirstOrDefault(x =>
x.GetDeclaredProperty("functionCode") != null &&
 (byte)x.GetDeclaredProperty("functionCode").GetValue(null) == val);
Run Code Online (Sandbox Code Playgroud)

它也不起作用。它引发System.Reflection.TargetException:非静态方法需要一个目标。

c# system.reflection

4
推荐指数
1
解决办法
3万
查看次数

如何使用Reflection创建带有参数的内部构造函数的实例?

我有一个不同的场景.我需要创建一个公共类的实例,但它的所有构造函数都是内部的.该类没有默认构造函数.

我尝试了以下方法,但它没有用.

Activator.CreateInstance(typeof(ClassName));
Activator.CreateInstance(typeof(ClassName), nonpublic:true);
Activator.CreateInstance(typeof(ClassName),true);
Activator.CreateInstance(typeof(ClassName), new object[]{double,bool});
Run Code Online (Sandbox Code Playgroud)

我也试过这个,但最终得到了System.MissingMethodException.

var constructors = typeof(ClassName).GetConstructors();
foreach(var ctor in constructors)
    ctor.Invoke(new object[] {double, bool});
Run Code Online (Sandbox Code Playgroud)

无法在Xamrarin中使用BindingFlags.我被卡住,有人有解决方案吗?

c# reflection system.reflection

4
推荐指数
1
解决办法
803
查看次数

为什么我们需要反思呢?

我正在研究Reflection,我得到了一些但是我没有得到与这个概念相关的一切.为什么我们需要反思?我们无法实现哪些事情需要反思?

.net c# asp.net reflection system.reflection

4
推荐指数
2
解决办法
352
查看次数