开发者

passing as parameter an object derived from a class in C#

开发者 https://www.devze.com 2023-03-22 11:07 出处:网络
As you all know using java it is possible to create methods which require one or more objects extended from another class; to do this you have to write:

As you all know using java it is possible to create methods which require one or more objects extended from another class; to do this you have to write:

public void method(Class<? extends class_name> Objec开发者_开发知识库t_name)

I was wondering whether there is a corresponding statement in C#. Does anybody know?


Well, that's accepting a type rather than an object, but you can do something slightly similar with generic methods in C#:

public void Foo<T>() where T : MyClass

Then you can use typeof(T) within the method.

If you need to specify an actual object compatible with type T, you can have that as a normal method parameter of type T.

If you need more, please update your question with more specific requirements.


you can make your method signature Generic and use a constraint

eg:

public static ObjectB GetObjectBFromInterface<T>(T item) where T : IObject
{
    //Do some stuff
}

see here for more information on Generic Type Constraints


You can write a generic method and use a type parameter constraint:

public void Method<T>(T obj) where T : YourBaseClass
{
    // ...
}


I haven't coded in Java in years, so I'm not familiar with the <? extends construct, however, I think you are asking how to pass in an interface or abstract class to a method.

You could use generics, but I think you would be better off just using the base class

public void Method(BaseClass baseClassParamName) 
{
   baseClassParamName.HasAccessToMethodsDefinedInTheBase();
}
0

精彩评论

暂无评论...
验证码 换一张
取 消