我试图围绕反射,所以我决定将插件功能添加到我正在编写的程序中.理解一个概念的唯一方法是让你的手指变脏并编写代码,所以我选择了创建一个由IPlugin和IHost接口组成的简单接口库,一个实现IPlugin的类的插件实现库,以及一个简单的接口库.实例化IHost实现类的控制台项目,该类实现了插件对象的简单工作.
使用反射,我想迭代我的插件实现dll中包含的类型并创建类型的实例.我能够使用此代码成功实例化类,但我无法将创建的对象强制转换为接口.
我尝试了这段代码,但我无法像我预期的那样投射对象o.我使用调试器完成了整个过程,并调用了正确的构造函数.快速查看对象o向我展示了它具有我期望在实现类中看到的字段和属性.
loop through assemblies
loop through types in assembly
// Filter out unwanted types
if (!type.IsClass || type.IsNotPublic || type.IsAbstract )
continue;
// This successfully created the right object
object o = Activator.CreateInstance(type);
// This threw an Invalid Cast Exception or returned null for an "as" cast
// even though the object implemented IPlugin
IPlugin i = (IPlugin) o;
Run Code Online (Sandbox Code Playgroud)
我使用这个代码.
using System.Runtime.Remoting;
ObjectHandle oh = Activator.CreateInstance(assembly.FullName, type.FullName);
// This worked as I intended
IPlugin i = (IPlugin) oh.Unwrap(); …Run Code Online (Sandbox Code Playgroud) 我从加载的程序集中读取类型,例如:
var someType = loadedAssemblies
.Where(a => a != null && a.FullName.StartsWith("MY."))
.SelectMany(a => a.GetTypes())
.Distinct()
.ToArray()[0];
Run Code Online (Sandbox Code Playgroud)
如果counstructor有参数,我可以读它们:
ParameterInfo[] parameters = classType.GetConstructors()[0].GetParameters();
Run Code Online (Sandbox Code Playgroud)
我想用默认参数值调用构造函数,或者如果参数是枚举,则使用第一个枚举值.如果只有一个参数并且它是枚举,则它的工作方式如下:
object curObject = Activator.CreateInstance(classType, new object[] { parameters[0].ParameterType.GetEnumValues().GetValue(0) });
Run Code Online (Sandbox Code Playgroud)
如果有更多参数,我该怎么做?我需要创建对象来读取属性:
var propertyInfo = someType.GetProperty("EntityType");
string entityType = propertyInfo.GetValue(curObject, null).ToString();
Run Code Online (Sandbox Code Playgroud) 我使用的共享下一个C#代码示例大卫赫弗南 "为从应用程序的资源加载.NET程序集,并从内存中运行它:
Assembly a = Assembly.Load(bytes);
MethodInfo method = a.EntryPoint;
if (method != null)
method.Invoke(a.CreateInstance(method.Name), null);
Run Code Online (Sandbox Code Playgroud)
在这里,我只是在VB.NET中分享我正在使用的改编:
Public Shared Sub Execute(ByVal resource As Byte(), ByVal parameters As Object())
Dim ass As Assembly = Assembly.Load(resource)
Dim method As MethodInfo = ass.EntryPoint
If (method IsNot Nothing) Then
Dim instance As Object = ass.CreateInstance(method.Name)
method.Invoke(instance, parameters)
If (instance IsNot Nothing) AndAlso (instance.GetType().GetInterfaces.Contains(GetType(IDisposable))) Then
DirectCast(instance, IDisposable).Dispose()
End If
instance = Nothing
method = Nothing
ass = Nothing
Else
Throw New …Run Code Online (Sandbox Code Playgroud) 在Scala中查询对象的类或类名时,您将$在打印输出的尾端获得一个流氓美元符号(" "):
object DollarExample {
def main(args : Array[String]) : Unit = {
printClass()
}
def printClass() {
println(s"The class is ${getClass}")
println(s"The class name is ${getClass.getName}")
}
}
Run Code Online (Sandbox Code Playgroud)
结果如下:
The class is class com.me.myorg.example.DollarExample$
The class name is com.me.myorg.example.DollarExample$
Run Code Online (Sandbox Code Playgroud)
当然,最后手动删除" $" 很简单,但我想知道:
我一直在想如何委托属性("by -Keyword")如何工作.
我通过契约获得了委托("by"的右侧)必须实现get和setValue(...)方法,但是如何通过编译器确保这一点以及如何在运行时访问这些方法?
我最初的想法是,代表们显然必须实现某种"SuperDelegate" - 接口,但似乎并非如此.
所以剩下的唯一选择(我所知道的)就是使用Reflection来访问那些方法,这些方法可能在语言本身的低层实现.我发现这有些奇怪,因为根据我的理解,这将是相当低效的.此外,Reflection API甚至不是stdlib的一部分,这使得它更加怪异.
我假设后者已经(部分)答案了.所以让我进一步问你以下内容:为什么没有SuperDelegate-Interface声明我们被迫使用的getter和setter方法呢?那不是更干净吗?
以下问题不是必不可少的
所描述的接口甚至已经在ReadOnlyProperty和ReadWriteProperty中定义.然后决定使用哪一个可以依赖于我们是否有val/var.或者甚至省略,因为编译器阻止在val上调用setValue方法,并且只使用ReadWriteProperty-Interface作为SuperDelegate.
可以说,当要求委托实现某个接口时,该构造的灵活性会降低.虽然这可以假设用作代表的类可能没有意识到这样使用,但鉴于对必要方法的具体要求,我认为不太可能.如果你仍然坚持,这里有一个疯狂的想法:为什么不通过扩展使该类实现所需的接口(我知道现在不可能,但是,为什么不呢?可能有一个好的'为什么不',请作为旁注告诉我.
我想动态生成程序集,它可以具有不同结构的函数.更准确地说,这些函数可以是递归的,它们可以调用同一程序System.Reflection集中的其他函数等.我找到了理论上提供工具的模块,但实际上我遇到了这种方法的许多缺点.例如 - 我不能通过TypeBuilder和MethodBuilder类生成递归函数,因为将抛出异常(使用不完整类型).我了解到我可以通过以下方式生成自递归函数IlGenerator- 但它太麻烦了 - 我希望有一种更简单的方法可以做到这一点.
这是我的程序,它演示了这个问题(在生成方法时Fact抛出以下异常:
Run Code Online (Sandbox Code Playgroud)Exception thrown: 'System.NotSupportedException' in mscorlib.dll Additional information: Specified method is not supported..
代码:
using System;
using System.Reflection;
using System.Reflection.Emit;
using System.Linq.Expressions;
namespace GenericFuncs
{
public class ProgramBuilder
{
public Type createMyProgram()
{
var assmName = new AssemblyName("DynamicAssemblyExample");
var assmBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assmName, AssemblyBuilderAccess.RunAndSave);
var moduleBuilder = assmBuilder.DefineDynamicModule(assmName.Name, assmName.Name + ".dll");
var myProgramType = buildMyProgram(moduleBuilder, moduleBuilder.DefineType("MyProgram", TypeAttributes.Public));
assmBuilder.Save(assmName.Name + ".dll");
return myProgramType;
}
private …Run Code Online (Sandbox Code Playgroud) 以下程序将打印字段以及是否使用常量 IsLiteral
public static class Program
{
public static void Main(string[] args)
{
foreach (var field in typeof(Program).GetFields())
{
System.Console.WriteLine(field.Name + " IsLiteral: " + field.IsLiteral);
}
System.Console.ReadLine();
}
public const decimal DecimalConstant = 99M;
public const string StringConstant = "StringConstant";
public const int IntConstant = 1;
public const double DoubleConstant = 1D;
}
Run Code Online (Sandbox Code Playgroud)
它适用于所有类型,除了decimalis将返回false.
谁能解释这种行为?是否有更好的方法来查看字段是否恒定?
如何检查类型T是否符合unmanaged类型约束,以便可以在以下上下文中使用:class Foo<T> where T : unmanaged?我的第一个想法是typeof(T).IsUnmanaged或类似的东西,但这不是Type班级的属性/领域
问题
我正在创建一个应用程序.在这个应用程序中,我正在使用序列化Func.这种方式不知何故使我的应用程序崩溃了.
崩溃毫无例外让我对wtf感到好奇,所以我做了一些深度潜水,经过一些挖掘后终于发现Newtonsoft.Json中的某个地方List.Contains正在发生,然后对2个属性执行等于检查.
显然在此等于检查会导致无限循环,从而导致堆栈溢出异常.
仅使用C#重现问题
Expression<Func<string, int>> expr = (t) => t.Length;
Func<string, int> exprCompiled = expr.Compile();
var aa = exprCompiled.Method.Module;
var bb = exprCompiled.Method.Module.Assembly;
//This code results in either an infinite loop or a Stackoverflow Exception
var tempresult = aa.Equals(bb);
Console.WriteLine("This code is never executed");
Run Code Online (Sandbox Code Playgroud)
使用Newtonsoft.Json重现问题
Expression<Func<string, int>> expr = (t) => t.Length;
Func<string, int> exprCompiled = expr.Compile();
//This code results in either an infinite loop or a Stackoverflow Exception
var res = JsonConvert.SerializeObject(exprCompiled);
Console.WriteLine("This code is …Run Code Online (Sandbox Code Playgroud) 我有一个使用的类 org.reflections.Reflections在类路径中的类中获取注释。
当我在同一个项目中使用它时一切正常,但是当我将它导出为 JAR 并在不同的类中引用它时,我得到以下执行:
Exception in thread "main" org.reflections.ReflectionsException: Scanner TypeAnnotationsScanner was not configured
at org.reflections.Store.get(Store.java:39)
at org.reflections.Store.get(Store.java:61)
at org.reflections.Store.get(Store.java:46)
at org.reflections.Reflections.getTypesAnnotatedWith(Reflections.java:429)
Run Code Online (Sandbox Code Playgroud)
这是代码片段:
System.out.println("Package to Scan: "+getPackageName());
final Reflections reflections = new Reflections(getPackageName(), new TypeAnnotationsScanner());
final Set<Class<?>> handlerClasses = reflections.getTypesAnnotatedWith(HandlerMapping.class,true);
Run Code Online (Sandbox Code Playgroud)
我确实提供了一个TypeAnnotationsScanner对象,但问题仍然存在。
注意:只有当上面的代码被称为 jar 时,它才起作用。(我使用 maven-assembly 插件创建了一个胖罐子)
任何指针?