编译

首先了解下,如何区分编译生成的 .dll的版本
方法1:ILSpy反编译工具

通过 assembly属性,release版本没有或仅有如下一种属性

[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]

而 debug版本,属性较多,示例

[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations |
DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]

具体参见:https://blog.csdn.net/WPwalter/article/details/80933080

方法2:代码检测

public static class Utils
{
//新增扩展方法
public static T GetCustomAttribute<T>(this ICustomAttributeProvider provider)
where T : Attribute
{
var attributes = provider.GetCustomAttributes(typeof(T), false);
return attributes.Length > 0 ? attributes[0] as T : default(T);
} public enum DllMode { Debug = 0, Release = 1 }; public static DllMode CheckDllMode_1(string _filePath)
{
var assembly = Assembly.LoadFile(_filePath);
var attributes = assembly.GetCustomAttributes(typeof(DebuggableAttribute), false);
if (attributes.Length > 0)
{
var debuggable = attributes[0] as DebuggableAttribute;
if (debuggable != null) {
return ((debuggable.DebuggingFlags & DebuggableAttribute.DebuggingModes.Default)
== DebuggableAttribute.DebuggingModes.Default)
? DllMode.Debug : DllMode.Release;
} else { return DllMode.Release; }
} else { return DllMode.Release; }
} public static DllMode CheckDllMode_2(string _filePath)
{
Assembly ass = Assembly.LoadFile(_filePath);
DebuggableAttribute att = ass.GetCustomAttribute<DebuggableAttribute>();
return (att != null && att.IsJITTrackingEnabled) ? DllMode.Debug : DllMode.Release;
} }

具体参见:https://www.oschina.net/code/snippet_12_8459

新增扩展方法时,若提示: 缺少编译器要求的成员“system.Runtime.CompilerServices.ExtensionAttribute..ctor”
解决方法,在当前.cs中添加

namespace System.Runtime.CompilerServices {
public class ExtensionAttribute : Attribute { }
}

反射

类Assembly中Load, LoadFrom, LoadFile方法比较

下面给出2种程序集加载方法

//方法1:直接从DLL路径加载 ok
assembly = Assembly.LoadFrom(assemblyPath); //方法2:先把DLL加载到内存,再从内存中加载 ok
using (FileStream fs = new FileStream(assemblyPath, FileMode.Open, FileAccess.Read))
{
using (BinaryReader br = new BinaryReader(fs))
{
byte[] bFile = br.ReadBytes((int)fs.Length);
br.Close();
fs.Close();
assembly = Assembly.Load(bFile);
}
}

可以将程序集中定义的所有类型暂存备用,调用时指定程序集和方法名即可

// htTypes是Hashtable
foreach (Type tp in assembly.GetTypes()) {
htTypes.Add(tp.Name, tp);
} string className = "Calculator.Calculator"; //程序集.类名
string funName = "Add"; //方法名
if (TypeTest.htTypes.ContainsKey(className))
{
var tp = (Type)TypeTest.htTypes[className];
var func = tp.GetMethod(funName);
if (null != func)
{
func.Invoke(null, new object[] { ... });
}
}

对于设置或获取字段或属性的值,注意区分静态/非静态

非静态的实例字段或属性,GetValue和SetValue时,第一个参数务必传入实例对象

object obj = Activator.CreateInstance(type, true);

而静态的,直接送null即可。设置时,保险起见可以作类型转换

var v = Convert.ChangeType(value, tp.GetField/GetProperty(_name).FieldType/PropertyType);

注,待加载的程序集可以在配置文件中配置。

  <configSections>
<section name="assembly" type="System.Configuration.NameValueSectionHandler"/>
</configSections> <!-- key为程序集名称,value表示是否要加载 -->
<assembly>
<add key="Calculator.dll" value="1"/>
<add key="crudHelper.dll" value="1"/>
</assembly>

代码中动态加载即可

NameValueCollection assemblyList = ConfigurationManager.GetSection("assembly") as NameValueCollection;

.Net框架提供了一个综合性方法:Type.InvokeMember,但是参数较多,慎用。

应用

[1]. 获取当前执行的方法的信息:2种

MethodBase method = MethodBase.GetCurrentMethod();
string tag = method.ReflectedType.FullName + "." + method.Name; //类名.方法名 StackTrace stackTrace = new StackTrace(true);
MethodBase method = stackTrace.GetFrame(0).GetMethod();
string codeDestination = method.DeclaringType.Name + "-" + method.Name; //类名.方法名

若要获取父方法的信息,使用 GetFrame(1) 即可。

[2]. 提取类实例字段名和字段值

public static string GetAllKeyValue<T>(T t, IDictionary<string, object> dic, bool removeEmptyVal)
{
if (t == null || dic == null) { return "t||dic null"; } try {
System.Reflection.PropertyInfo[] properties = t.GetType().GetProperties(
System.Reflection.BindingFlags.Instance |
System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public);
if (properties.Length <= 0) { return "properties 0"; } foreach (System.Reflection.PropertyInfo item in properties) {
string name = item.Name;
object value = item.GetValue(t, null); if (item.PropertyType.IsValueType || item.PropertyType.Name.StartsWith("String")) {
if (removeEmptyVal && (value == null ||
(value is string && string.IsNullOrWhiteSpace(value.ToString())))) { /* not save empty value */ }
else { dic.Add(name, value); }
} else {
GetAllKeyValue(value, dic, removeEmptyVal);
}
}
} catch (Exception ex) {
return ex.Message + "||" + ex.StackTrace;
}
return string.Empty;
}

其中GetProperties()中的参数可以按需控制。

C# - 反射与编译的更多相关文章

  1. Java学习:注解,反射,动态编译

    狂神声明 : 文章均为自己的学习笔记 , 转载一定注明出处 ; 编辑不易 , 防君子不防小人~共勉 ! Java学习:注解,反射,动态编译 Annotation 注解  什么是注解 ? Annotat ...

  2. 【UE4】基础概念——文件结构、类型、反射、编译、接口、垃圾回收、序列化

    新标签打开或者下载看大图 思维导图 Engine Structure Pipeline Programming Pipeline Blueprint Pipeline

  3. 初识Scala反射

    我们知道,scala编译器会将scala代码编译成JVM字节码,编译过程中会擦除scala特有的一些类型信息,在scala-2.10以前,只能在scala中利用java的反射机制,但是通过java反射 ...

  4. Java中的反射和注解

    前言 在Java中,反射机制和注解机制一直是一个很重要的概念,那么他们其中的原理是怎么样呢,我们不仅仅需要会使用,更要知其然而之所以然. 目录 反射机制 反射如何使用 注解定义 注解机制原理 注解如何 ...

  5. 【C#进阶系列】23 程序集加载和反射

    程序集加载 程序集加载,CLR使用System.Reflection.Assembly.Load静态方法,当然这个方法我们自己也可以显式调用. 还有一个Assembly.LoadFrom方法加载指定路 ...

  6. java 面向对象编程-- 第十三章 反射、类加载与垃圾回收

    1.狭义JavaBean规范 Javabean必须包含一个无参数的public构造方法,方便通过反射的方式产生对象. 属性必须都是私有的. Javabean必须包含符合命名规范的get和set方法,以 ...

  7. 浅说Java中的反射机制(二)

    写过一篇Java中的反射机制,不算是写,应该是抄了,因为那是别人写的,这一篇也是别人写的,摘抄如下: 引自于Java基础--反射机制的知识点梳理,作者醉眼识朦胧.(()为我手记) 什么是反射? 正常编 ...

  8. 初识Java反射

    要详细的了解Java反射,就得要了解Java的类加载以及何为运行时动态加载等等概念.本文抛开其余概念,简单介绍Java反射,详细介绍会在以后有一个系统而全面的认识过后展开. 反射是Java被视为动态语 ...

  9. .NET Core单文件发布静态编译AOT CoreRT

    .NET Core单文件发布静态编译AOT CoreRT,将.NET Core应用打包成一个可执行文件并包含运行时. 支持Windows, MacOS and Linux x64 w/ RyuJIT ...

随机推荐

  1. 原生JS 实现元素排序

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...

  2. Crash以及报错总结

    CoreData: Cannot load NSManagedObjectModel.nil is an illegal URL parameter 这是因为在工程中CoreData的命名和AppDe ...

  3. VMware + LInux + Xshell 连接环境设置(心得体会)

    准备好VMware软件,和Linux 和xshell三款软件,下载和安装好,这里VMware是十二,Linux是CentOs 6 ,xshell是5 其实没有什么区别只要版本兼容就行,我们就可以实现远 ...

  4. 用node.js写个在Bash上对字符串进行Base64或URL的encode和decode脚本

    一:自己这段时间经常要用到Base64编码和URL编码,写个编译型语言有点麻烦干脆就用node.js弄了个,弄好后在/etc/profile里加上alias就能完成工具的配置,先上代码: functi ...

  5. 解决Web Uploader上传文件和图片 延迟和not defined

    1.出现list not define时,var $list = $("#fileList"); 2.选择文件框有延迟,可能是因为选择文件类型过多 mimeTypes: 'imag ...

  6. WriteableBitmap(三) 扩展

    backbuffer使用您在创建WriteableBitmap时指定的像素格式,还有一个BackBufferStride属性,您可以使用它来创建一个合适的存储映射函数. 添加一些方法来设置和获取特定情 ...

  7. (线段树 区间查询更新) Can you answer these queries? -- hdu--4027

    链接: http://acm.hdu.edu.cn/showproblem.php?pid=4027 分析:因为这个操作是把一个数变成平方根,所以显得略棘手,不过如果仔细演算的话会发现一个2^64数的 ...

  8. PHP 7 安装 Memcache 和 Memcached 总结

    Memcache 与 Memcached 的区别 Memcached 是 Memcache 的升级版,优化了 Memcache,并增加了一些操作方法.所以现在基本都是用最近版本的. PHP 7 下安装 ...

  9. springmvc 开涛 数据验证

    两种方式:编程和声明. 编程需要:验证器,控制器,servlet.xml,错误码设置 声明需要:加jar包,控制器,跟孔浩讲得类似 错误消息设置的两种方式:硬编码:从资源文件中读取(默认,自定义).

  10. 集合(一)ArrayList

    前言 这个分类中,将会写写Java中的集合.集合是Java中非常重要而且基础的内容,因为任何数据必不可少的就是该数据是如何存储的,集合的作用就是以一定的方式组织.存储数据.这里写的集合,一部分是比较常 ...