2013-05-02 76 views
2

我有一個使用「yield」return語句的單一方法。嵌套類型自動創建。使用反射和綁定標誌設置爲BindingFlags.DeclaredOnly,我得到這個輸出:反射和自動生成類型

//我的班的公共成員。
Test.FileSystemObject..ctor
Test.FileSystemObject.GetFiles(DirectoryInfo的目錄)
Test.FileSystemObject.GetFiles(字符串路徑)

// Auto generated nested class. 
Test.FileSystemObject+<GetFiles>d__4..ctor 
Test.FileSystemObject+<GetFiles>d__4.<>3__directory 
Test.FileSystemObject+<GetFiles>d__4.<>4__this 
Test.FileSystemObject+<GetFiles>d__4.<directories>5__7 
Test.FileSystemObject+<GetFiles>d__4.<files>5__8 
Test.FileSystemObject+<GetFiles>d__4.<FSO>5__6 
Test.FileSystemObject+<GetFiles>d__4.<i>5__9 
Test.FileSystemObject+<GetFiles>d__4.<unprocessed>5__5 
Test.FileSystemObject+<GetFiles>d__4.directory 

如何確定通過assembly.GetTypes(BindingsFlags)返回的類型是否爲這樣的自動生成類型?我正在尋找一種簡單的方法來排除這些。

+0

@Thomas Levesque的:我測試你的代碼,它的工作。但是,它在使用ReflectionOnlyLoadFrom(path)加載程序集時引發了異常。快速搜索後,使用CustomAttributeData.GetCustomAttribute(type)並將每個attribute.ToString()與「[System.Runtime.CompilerServices.CompilerGeneratedAttribute()]」進行比較。謝謝。 – bricklayer137 2013-05-03 18:18:18

回答

5

您可以測試,如果該類型有[CompilerGenerated]屬性:

if (type.GetCustomAttribute(typeof(CompilerGeneratedAttribute), true) != null) 
{ 
    ... 
} 

或者,你可以檢查,如果名稱中包含的字符,不會在用戶代碼有效。

+0

具體來說,我相信所有由C#編譯器生成的類型都包含'<' and '>'。雖然這顯然是一個實現細節。 – svick 2013-05-03 02:18:58

+1

@svick:細節在這裏,是的,他們可能會改變:http://stackoverflow.com/questions/2508828/where-to-learn-about-vs-debugger-magic-names/2509524#2509524 – 2013-05-03 05:47:49

0

您可以在運行時編寫代碼,使用CSharpCodeProvider().CompileAssemblyFromSource()進行編譯並在當前程序集域中註冊您的類型。 只要域存在,它就會駐留在那裏。從結果中調用'get'訪問器會自動從編譯後的程序集中調用'Load'方法到當前的應用程序域中。

您也可以使用Reflection.Emit.TypeBuilder.CreateType()來創建您的類型。此外,您可以強制將屬性標誌顯示爲編譯器生成的或此處的其他屬性。

var infoConstructor = typeof(CompilerGeneratedAttribute).GetConstructor(Type.EmptyTypes); 

typeBuilder.SetCustomAttribute(infoConstructor, new byte[] { }); 

這就是我今天工作​​的例子。它的目的更多是爲了視覺目的,作爲一個自動生成的所有類代碼逆向工程的實體集合。似乎比使用文件I/O w/T4和XML輸出轉儲更好。雖然,這可能是一個可行的選擇,然後X-Doc/oxygen會自動生成HTML維基頁面,並且可以在下一版本的PDB中使用和編譯代碼。不是英國媒體報的粉絲,留在反思。

/// <summary> 
    /// CreateType 
    /// </summary> 
    /// <param name="obj"></param> 
    /// <param name="name"></param> 
    /// <param name="properties"></param> 
    /// <param name="accessor"></param> 
    /// <param name="hasSubTypes"></param> 
    /// <returns>The newly created type of the object.</returns> 
    internal static Type CreateType(this Mirror obj, string name, IEnumerable<string> properties, string accessor = "", bool hasSubTypes = false) { 
     Type subTypeRef = null; 

     // Tested Regex @ http://regex101.com 
     const string subTypes = @"(?:<|(?:\$))([a-zA-Z_]+[0-9`]*)(?:>([a-zA-Z_]+[0-9`]*))"; 
     var match = Regex.Match(name, subTypes); 

     if (match.Success) { 
     var refType = match.Groups[1].Value; // Class reference type. 
     if (match.Groups[2].Success && !string.IsNullOrEmpty(match.Groups[2].Value)) 
      accessor = match.Groups[2].Value; // Class accessor. 

     // ReSharper disable once TailRecursiveCall 
     var enumerable = properties as IList<string> ?? properties.ToList(); 
     subTypeRef = CreateType(obj, refType, enumerable, accessor, true); 

     // Tokenize this for the actual derived class name. 
     name = name.Substring(0, name.IndexOf('+')); 
     } 

     // Check if formating of the class name matches traditional valid syntax. 
     // Assume at least 3 levels deep. 
     var toks = name.Split(new[] { '+' }, StringSplitOptions.RemoveEmptyEntries); 
     Type type = null; 

     foreach (var tok in toks.Reverse()) { 
     var o = obj.RefTypes.FirstOrDefault(t => t.Value.Name == tok); 
     if (!o.Equals(default(KeyValuePair<string, Type>))) 
      continue; 

     // Not exists. 
     var sb = new StringBuilder(); 
     sb.Append(@" 
using System; 
using System.Runtime.CompilerServices; 
using System.Collections.Generic; 
using System.Linq; 

namespace HearthMirror.TypeBuilder { 
    [CompilerGenerated] 
    public class ").Append(tok).AppendLine(@" {"); 

     if (subTypeRef != null) 
      sb.AppendLine($" public {subTypeRef.Name} {accessor}").AppendLine(" { get; set; }"); 

     sb.Append(" }\n}"); 

     var asm = RuntimeCodeCompiler.CompileCode(sb.ToString()); 
     type = asm.GetType($"{MethodBase.GetCurrentMethod().ReflectedType?.Namespace}.{tok}"); // => generated 

     // Register our type for reference. This container will handle collisions and throw if encountered. 
     obj.RefTypes.Add(tok, type); 
     } 

     return type; 
    } 

/// <summary> 
/// CompileCode 
/// </summary> 
/// <param name="code"></param> 
/// <returns></returns> 
public static Assembly CompileCode(string code) { 
    var provider = new CSharpCodeProvider(); 
    var compilerparams = new CompilerParameters { GenerateExecutable = false, GenerateInMemory = true, IncludeDebugInformation = true }; 

    foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies()) { 
    try { 
     var location = assembly.Location; 
     if (!string.IsNullOrEmpty(location)) 
     compilerparams.ReferencedAssemblies.Add(location); 
    } catch (NotSupportedException) { 
     // this happens for dynamic assemblies, so just ignore it. 
    } 
    } 

    var results = provider.CompileAssemblyFromSource(compilerparams, code); 
    if (results.Errors.HasErrors) { 
    var errors = new StringBuilder("Compiler Errors :\r\n"); 
    foreach (CompilerError error in results.Errors) 
     errors.AppendFormat("Line {0},{1}\t: {2}\n", error.Line, error.Column, error.ErrorText); 
    throw new Exception(errors.ToString()); 
    } 
    AppDomain.CurrentDomain.Load(results.CompiledAssembly.GetName()); 
    return results.CompiledAssembly; 
}