2017-03-06 3 views
4

우선, 질문 제목에 대해 사과드립니다. 나는 그것이 성취하려고하는 것이 무엇인지 불렀는지 정말로 모르겠다. 그래서 나는 곧바로 그것을 바로 잡을 것이다.이 코드를 리팩터링하는 방법 (C#, Types)

저는 현재 C#에서 GDI +를 사용하여 게임 엔진을 개발 중이며 구성 요소 클래스를 구현했습니다. 아이디어는 어떤 게임 객체도 여러가지 구성 요소를 가질 수 있다는 것입니다 (Unity3D와 매우 비슷합니다). 어떤 유형의 구성 요소라도 찾을 수 있기를 원합니다.

Rigidbody r = obj.GetComponentOfType(typeof(Rigidbody)) as Rigidbody; 

이 대신 같이하려면 : 나는이 일에 대해 어떻게 가야합니까

Rigidbody r = obj.GetComponentOfType<Rigidbody>(); 

그 주에

이, 나는이 코드 조각을 변경하려면?

죄송합니다. 내 질문이 모호하게 보이는 경우이 주제에 대해 밝혀진 모든 것이 훌륭합니다!

+1

http://answers.unity3d.com/questions/55331/differences-generic-getcomponentscript-vs-getcompo.html – lordkain

답변

0

더티 작업 (게시 한 첫 번째 코드 줄)을 수행하고 일반 형식을 허용하는 확장 메서드를 GetComponentOfType 메서드에 추가합니다. 그런 다음 <> 태그의 리지드 바디 유형을 전달할 수 있습니다.

확장 방법에 대한 자세한 내용은 here을 참조하십시오.

편집 : 확장 방법이 정적인지 확인하십시오.

희망이 있습니다.

3

obj 유형에 List<Component> 필드가 있다고 가정합니다. 당신은 Linq를 사용할 수 있습니다

// assuming 
public class GameObject 
{ 
    List<Component> m_Components; // all components attached to this GameObject 
    public TComponent GetComponentOfType<TComponent>() 
     where TComponent : Component 
    { 
     // Select only the ones of type TComponent and return first one 
     return m_Components.OfType<TComponent>().FirstOrDefault(); 
    } 
} 

를이 사용하기 : 이것은 일반적인 방법이라고

public static T GetComponentOfType<T>(this [objType] obj) 
where T : class 
{ 
    return obj.GetComponentOfType(typeof(T)) as T; 
} 
1

당신이 클래스를 변경할 수없는 경우, 당신은 확장 방법을 사용할 수 있습니다 . 다음과 같이 기존 형식 기반 구현을 호출하는 오버로드를 만들 수 있습니다.

public T GetComponentOfType<T>() 
{ 
    return (T) GetComponentOfType(typeof(T)); 
} 
7

: obj.GetComponentOfType<Rigidbody>();

0

이것은 제네릭을 사용하여 수행됩니다. GetComponentofType 메서드의 본문은 거의 동일하지만 유일한 차이점은 매개 변수로 전달하는 대신 generic을 통해 원하는 형식을 지정한다는 점입니다.

public T GetComponentOfType<T>(){ 

     //code goes here to locate the object. 
     you can get the type via typeof(T) 

     return theObject; 
} 
0

public class Rigidbody{ 
 
     public int Size{ get; set; } 
 
     public string fourgroundColor{ get; set; } 
 
     public string backgroundColor{ get; set; } 
 
     public int fingerammount{ get; set; } 
 
     public int arms{ get; set; } 
 
    }

는 강체라는 클래스를 만들 :

방법처럼 보일 수 있습니다. 사용 가능한 것보다 모든 구성 요소를 클래스에 설정하십시오. Olso는 그것을 공개합니다. 그렇지 않으면 예제처럼 사용할 수 없습니다.

클래스가 있으면 다음과 같이 말할 수 있습니다. var r = obj.GetComponentOfType(); olso는 데이터 유형 대신 var를 사용합니다. var는 데이터 유형이 oldscool 인 것이 더 좋습니다 (C# 1 또는 C2와 같습니다).0) 나는 항상 같은 실수를 저질 렀다.

using System.Linq; 
using System.Collections.Generic; 

/// <summary> 
/// Base-Class 
/// </summary> 
public abstract class Thing 
{ 
    private ICollection<Thing> _things; 

    public Thing() 
    { 
     _things = new List<Thing>(); 
    } 

    public void AddSomething(Thing toAdd) 
    { 
     _things.Add(toAdd); 
    } 

    /// <summary> 
    /// Assuming that every type can only appear once 
    /// </summary> 
    /// <param name="t"></param> 
    /// <returns></returns> 
    public T GetComonentOfType<T>() where T : Thing 
    { 
     return this.GetComonentOfType(typeof(T)) as T; 
    } 

    public Thing GetComonentOfType(Type t) 
    { 
     return _things.Where(x => x.GetType() == t).Single(); 
    } 

} 

/// <summary> 
/// One possible implementation 
/// </summary> 
public class SpecialThing : Thing 
{ 

} 
+0

IMO이 대답은 전혀 의미가 없습니다. OP는 그의 구성 요소를 추출하기위한 제네릭 메소드를 생성하는 방법에 대해 질문했고, 컴파일 타임 타입 해석 메소드에 대해 쓰고 있습니다. –

1

VAR를 사용하라고 모든 구성 요소 클래스를 상속 가정이 클래스 (또는 모두) :

public abstract class IComponent 
{ 
    protected IList<object> objComponents; 

    public object GetComponentOfType(Type type) 
    { 
     if (objComponents == null) 
      return null; 

     return objComponents.Where(obj => obj.GetType() == type).FirstOrDefault(); 
    } 
} 
당신은 또 다른 주요 어머니 클래스를 만들 수 있습니다

로부터 상속받을 수 :

public abstract class BaseComponent : IComponent 
{ 
    public object GetComponentOfType<T>() 
    { 
     return GetComponentOfType(typeof(T)); 
    } 
} 

첫 번째 클래스에 대한 액세스 권한이있는 경우 이전 함수를 추가하면됩니다.

0

: 내가 sofware 개발자로 작업을 시작 할 때하지만 난 당신이 다음과 같은 일반적인 방법을 구현하려는 생각 (내가 olmost medior, 여전히 주니어 해요)