简体   繁体   English

C#反射分配

[英]C# Reflection Assignment

so I need some help with this. 所以我需要一些帮助。 I tried searching SOF, but I had no luck. 我尝试搜索SOF,但没有运气。

Using reflection, I need to test .NET String class. 使用反射,我需要测试.NET String类。 I need to show class name, interfaces that, this class implements, the assembly where this class is found, namespace of this class, type that inherits, and basic informations. 我需要显示类名称,该类实现的接口,找到该类的程序集,该类的名称空间,继承的类型以及基本信息。 Is this class abstract, generic, sealed etc. I had been learning this for 20 days, now, and I had no luck, so I was learning attributes, reflection, and assemblies, and metadata assemblies, EDIT: My question is: How to write this properly, I tried like 1000x, and nothing, always some mistakes, always errors, I do not know how to start.. 这个类是抽象的,泛型的,密封的等吗。我已经学习了20天,现在,我没有运气,所以我正在学习属性,反射和程序集以及元数据程序集,编辑:我的问题是:如何正确地写这个,我试过像1000x,什么也没有,总是有一些错误,总是有错误,我不知道如何开始。

class Program
{
    static void Main()
    {
        TellMeAboutType(typeof(string));
    }
    static void TellMeAboutType(Type type)
    {
        Console.WriteLine("Name: " + type.Name);
        Console.WriteLine("Namespace: " + type.Namespace);
        Console.WriteLine("Assembly: " + type.Assembly.FullName);
        Console.WriteLine("AQN: " + type.AssemblyQualifiedName);
        Console.WriteLine("Abstract: " + type.IsAbstract);
        Console.WriteLine("Generic: " + type.IsGenericType);
        Console.WriteLine("Sealed: " + type.IsSealed);
        Console.WriteLine("Base Type: " + type.BaseType.FullName);
        foreach(var iType in type.GetInterfaces())
        {
            Console.WriteLine("Implements: " + iType.FullName);
        }
    }
}

I know Marc already answered, but I wanted to answer the short version of the question "How to start with reflection?" 我知道Marc已经回答了,但我想回答问题“如何开始思考?”的简短版本。

Basically, you need a reference to the type. 基本上,您需要对类型的引用。 For that there are two methods: 1. In case you know the type (or it is a generic eg <T> ): typeof(MyType) or typeof(T) . 为此,有两种方法:1.如果您知道类型 (或者它是通用类型,例如<T> ): typeof(MyType)typeof(T) 2. In case you have an object instance, then you need to get the type first, which is also simple: myObject.GetType() 2.如果您有一个对象实例,则需要首先获取类型,这也很简单: myObject.GetType()

In both cases, then you just use the properties of the Type object you got, like Marc shown. 在这两种情况下,您都只需使用获得的Type对象的属性,如Marc所示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM