c# - 获取要分配的字段的 FieldInfo

标签 c# .net reflection

有什么方法可以获取要为该变量赋值的函数中字段的 FieldInfo 吗?

看我的例子:

class SomeClass{    
    MyType myObject = SomeOtherClass.MyFunction();
}

class SomeOtherClass{
    public static MyType MyFunction(){
        //Get FieldInfo about myObject here
    }
}

背景:

我想要做的是能够在“myObject”上设置一个属性,指定该对象应该缓存在“MyFunction”中。

最佳答案

抱歉,Herber,我尝试在评论中回复,但这对于评论来说太大了:

对于您在我上次回复中提到的情况,这对您有用吗?

    class Program
    {
        static void Main(string[] args)
        {
            SomeClass sc = new SomeClass();
        }
    }
    class SomeClass
    {
        public MyType myObject;
        public SomeClass()
        {
            SomeOtherClass.MyFunction(this);
        }
    }

    static class SomeOtherClass
    {
        public static void MyFunction(SomeClass sClass)
        {
            sClass.myObject = new MyType() { Name = "Test1" };
            FieldInfo[] fInfo = sClass.myObject.GetType().GetFields();
            Console.WriteLine(fInfo[0].GetValue(sClass.myObject));
        }
    }
    class MyType
    {
        public string Name;
    }

关于c# - 获取要分配的字段的 FieldInfo,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3266523/

相关文章:

c# - .NET 是否可以在组合框的项目上使用上下文菜单?

c++ - 如何向 C++ 应用程序添加反射?

c# - 使用反射从 Property.GetValue 返回对象列表

c# - 向菜单条添加标签

.net - 仅在 XAML 中更改 ListView 排序属性/方向

循环中的 C# WinForms 多线程

c# - UWP 的标题栏后退按钮

c# - 反射 - 作为接口(interface)的类的 GetProperties

c# - 为什么 float 和 int 具有如此不同的最大值,即使它们的位数相同?

c# - 无法将类型 'System.String' 的对象强制转换为 "..Controls.SurfaceListBoxItem' 异常