为什么只读变量“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) 我有几个接口(IMapFrom和IMapTo),可以让我简化AutoMapper配置。每个接口都有MapTo和MapFrom方法的默认实现。我有一个单独的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
我有以下代码适用于 .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) 我一直在这里阅读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?
我正在开发一个组件,它执行使用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.Load(typeName)但得到了null)我有一个 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#类:
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两种情况. …
在我的应用程序中,我从某个地方收到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:非静态方法需要一个目标。
我有一个不同的场景.我需要创建一个公共类的实例,但它的所有构造函数都是内部的.该类没有默认构造函数.
我尝试了以下方法,但它没有用.
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.我被卡住,有人有解决方案吗?
我正在研究Reflection,我得到了一些但是我没有得到与这个概念相关的一切.为什么我们需要反思?我们无法实现哪些事情需要反思?
c# ×10
reflection ×5
.net ×2
.net-4.0 ×1
.net-6.0 ×1
asp.net ×1
c#-8.0 ×1
c#-to-f# ×1
clr ×1
dictionary ×1
f# ×1
inlining ×1
jit ×1
linq ×1
performance ×1