簡體   English   中英

如何從List <Func <Int32>>中提取類名

[英]How to extract the class name out of List< Func< Int32 > >

如何從列表中刪除該名稱?

例如

static void Main()
{
    var methods = new List<Func<int>>();
    methods.Add(() => new ThisCss().useThis(0));

    // Output ThisCss here from methods
    // i.e Console.WriteLine(methods[0].ClassName).. or something like that

}

class ThisCss
{
    public int useThis(int num)
    {
       return 0;
    }
}

因此,為了澄清一下,我想從函數列表的0索引中獲取類的名稱。 因此,在這種情況下,它將是“ ThisCss”。

Func<...>是一個delegate ,所有delegate實例均派生自System.Delegate ,后者具有Method屬性,該屬性返回System.Reflection.MethodInfo ,其中包含有關所調用的實際CLR方法的元信息,包括其包含的類型/類(是CLR中沒有自由功能,所有功能都是方法)。

嘗試這個:

foreach( Func<Int32> f in methods ) {
    MethodInfo mi = f.Method;
    String typeName = mi.DeclaringType.FullName;
    Console.WriteLine( typeName + "." + mi.Name );
}

請注意,如果您引用匿名函數或Lambda函數,則實際的 DeclaringType將是C#編譯器生成的類型,其名稱具有不可預測或意外的名稱(您可以使用Ildasm,ILSpy或RedGate Reflector之類的CIL反匯編工具Ildasm該類型。

您試圖將一個函數調用分解為一個表達式樹。

您不能對普通的舊Func執行此操作,但是可以對System.Linq.Expressions.Expression執行此操作。

using System;
using System.Linq.Expressions;
using System.Collections.Generic;
using System.Reflection;

public class ThisCss
{
    public int useThis(int num)
    {
        return 0;
    }
}


public class Program
{
    public static Type ExtractClassType(Expression<Func<int>> methodCall)
    {
        if (methodCall.Body.NodeType == ExpressionType.Call)
        {
            MethodCallExpression memberExpression = (System.Linq.Expressions.MethodCallExpression)methodCall.Body;
            MethodInfo memberInfo = memberExpression.Method;
            return memberInfo.DeclaringType;
        }
        else
        {
            throw new InvalidOperationException("Unable to extract a method call from this expression");
        }
    }



    public static void Main()
    {
        var methods = new List<Expression<Func<int>>>();
        methods.Add(() => new ThisCss().useThis(0));

        var type = ExtractClassType(methods[0]);

        Console.WriteLine("{0}", type);
    }
}

如果可以更改返回類型,“元組”又如何呢?

var methods = new List<Tuple<string, Func<int>>>();

methods.Add(new Tuple<string, Func<int>>(nameof(ThisCss), () => new ThisCss().useThis(0)));
methods.Add(new Tuple<string, Func<int>>(nameof(ThisCss2), () => new ThisCss2().useThis(0)));

var className = methods[0].Item1;

在C#7.0中

var methods = new List<(string ClassName, Func<int> Func)>();

methods.Add((nameof(ThisCss), () => new ThisCss().useThis(0)));
methods.Add((nameof(ThisCss2), () => new ThisCss2().useThis(0)));

var className = methods[0].ClassName;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM