简体   繁体   English

如何获取对象的类型并将其作为参数传递给C#

[英]How to get the type of an object and pass it as a parameter in C#

ClassA , ClassB , ClassC and ClassD are all implementing IMyClass interface. ClassAClassBClassCClassD都实现IMyClass接口。

myObj is an instance of one of the classes. myObj是这些类之一的实例。

private void setObj<T>()
{
    myObj = mycollection.Single(w => w is T);
}

public void Switch()
{
    if(myObj is ClassA)
    {
        setObj<ClassA>();
    }
    else if(myObj is ClassB)
    {
        setObj<ClassB>();
    }
    else if(myObj is ClassC)
    {
        setObj<ClassC>();
    }
    else if(myObj is ClassD)
    {
        setObj<ClassD>();
    }
}

How can we refactor the Switch method, so that I have something like this: 我们如何重构Switch方法,这样我就有了这样的东西:

public void Switch()
{
    // How can we know from `myObj`, which class it is and rewrite 
    // the whole Switch method like this
    // X = `ClassA`, `ClassB`, `ClassC` or `ClassD`

    setObj<X>();

}

You cannot pass a generics type parameter as a variable in C# . 您不能在C#中将泛型类型参数作为变量传递 However, you can get the type via reflection ( myObj.GetType() ) and pass that as a function parameter from your Switch() function to your setObj() function, which in turn can be compared in your lambda: 但是,您可以通过反射( myObj.GetType() )获取类型,并将其作为函数参数从Switch()函数传递给setObj()函数,而后者又可以在lambda中进行比较:

    private void setObj(Type type)
    {
        myObj = Objects.Single(o => o.GetType() == type);
    }

    public void Switch()
    {
        Type setToThisType = myObj.GetType();
        setObj(setToThisType);
    }

make Switch a generic method too that accepts an object of type T 也使Switch成为通用方法,该方法接受类型Tobject

public void Switch<T>(T obj) where T : IMyClass
{
    setObj<T>();
}

The where T : IMyClass statement ensures that you can only call Switch where obj is an instance of a class implementing IMyClass where T : IMyClass语句确保您只能在obj是实现IMyClassclassinstance下调用Switch

    void Example()
    {
        ClassA objA = new ClassA();
        Switch(objA); //OK;

        ClassX objX = new ClassX();
        Switch(objX); //compile-time error since ClassX doesn't implement IMyClass
    }

EDIT: after reading the title, I think you would need to have the parameter T obj in the Switch method. 编辑:阅读标题后,我认为您需要在Switch方法中具有参数T obj

Try using typeof(ClassA) 尝试使用typeof(ClassA)

public void TypeTest(Type t)
{
   if(t.Equals(typeof(ClassA))){
   }
}

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

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