How can I rewrite this a generic?

Vaughan Hilts

I have the following piece of code:

 public Component GetComponent(Type type)
    {
        return Components.FirstOrDefault(component => component.GetType() == type);
    }

The caller has to do a nasty cast to get the component it passed in - how can I rewrite this to a cast-less generic?

Scott Chamberlain

If I read your question correctly, you can move the cast inside the function and do it this way.

public T GetComponent<T>() where T : Component
{
    return (T)Components.FirstOrDefault(c => c.GetType() == typeof(T));
}

If the type is not known at compile time going in to the function (like, say GetComponet() is called in a loop where the type is passed in as a argument) there is no way to get a strongly typed object back.

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

분류에서Dev

How can I rewrite my controller URL?

분류에서Dev

How can I rewrite everything but my first rule in htaccess?

분류에서Dev

How can I rewrite the native HTML input element with Polymer?

분류에서Dev

In R, how can I see the signatures for which a generic method is implemented?

분류에서Dev

Q.js: How can I rewrite an async series flow in Q.js?

분류에서Dev

Can I require generic parent directive in AngularJS

분류에서Dev

How Can I Force .NET (C#) to Use the non-generic overload of a method?

분류에서Dev

how can i determine the ACTUAL return type of a specific subclass of a generic superclass?

분류에서Dev

Java: How do I write a generic method?

분류에서Dev

How can convert mod_rewrite rules to nginx rules

분류에서Dev

How do I use an extended generic type's type in a class?

분류에서Dev

How do I rewrite my SQL query to remove redundant values from a GROUP BY column?

분류에서Dev

How can I perform an OR with ScalaTest

분류에서Dev

How can I run owncloud?

분류에서Dev

How can I organize this array

분류에서Dev

How can I get a RejectedExecutionException

분류에서Dev

How can i manage this request?

분류에서Dev

How can I rotate a Rectangle?

분류에서Dev

How can I get a solution for this?

분류에서Dev

How can I foreach a hashmap?

분류에서Dev

How can I stop the timer?

분류에서Dev

How can I repack JPEG?

분류에서Dev

How i can use a criteria in cicle for i

분류에서Dev

How can I run a desktop in the cloud that I can remotely connect to?

분류에서Dev

How to enable mod_rewrite?

분류에서Dev

How to rewrite an char array in c?

분류에서Dev

How to rewrite an url via htaccess

분류에서Dev

If I have apply(i: Int), how can I have map?

분류에서Dev

How to accept generic iterators?

Related 관련 기사

뜨겁다태그

보관