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?
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] 삭제
몇 마디 만하겠습니다