C #의 함수에서 제네릭 형식의 속성에 액세스

Icen

일반 메서드가있는 인터페이스가 필요합니다. 그러나 해당 인터페이스의 각 구현은 해당 유형을 알고 있습니다.

class Program
{
    static void Main(string[] args)
    {

        var specificContext = new SpecificContext();

        var res = new SrvThatCantBeGeneric().GetValueFromSpecificContext(specificContext);
        Console.WriteLine(res);
    }

}
public class SrvThatCantBeGeneric : ISrvThatCantBeGeneric
{
    public int GetValueFromSpecificContext<SpecificContext>(SpecificContext specificContext)
    {
        return specificContext.MyProperty; // <-- this is where it breaks
    }
}

public interface ISrvThatCantBeGeneric
{        
    int GetValueFromSpecificContext<T>( T specificContext);
}

public class SpecificContext
{
    public int MyProperty { get; set; } = 42;
}

어떤 이유로 내가 위의 방식으로 할 때 작동하지 않고 다음과 같이 말합니다.

'SpecificContext'에 'MyProperty'에 대한 정의가 포함되어 있지 않으며 'SpecificContext'유형의 첫 번째 인수를 허용하는 액세스 가능한 확장 메서드 'MyProperty'를 찾을 수 없습니다 (using 지시문 또는 어셈블리 참조가 누락 되었습니까?).

왜 이런 일이 발생하고 어떻게 해결합니까?

다음과 같이 제네릭 유형의 정의를 이동하여 수정할 수 있습니다.

public class SrvThatCantBeGeneric : ISrvThatCantBeGeneric<SpecificContext>
{
    public int GetValueFromSpecificContext(SpecificContext specificContext)
    {
        return specificContext.MyProperty; // <-- this is where it breaks
    }
}

public interface ISrvThatCantBeGeneric<T>
{        
    int GetValueFromSpecificContext( T specificContext);
}

그러나 이것은 코드의 다른 부분에서 중단되며 진행되지 않습니다.

편집 : 내 코드 단순화

올리비에 로지에

작성하여 :

public int GetValueFromSpecificContext<SpecificContext>(SpecificContext specificContext)

범위를 "재정의"하고 여기 SpecificContext에이 이름을 가진 클래스를 마스킹하는 일반 유형 매개 변수가 있으므로 다음과 동일합니다.

public int GetValueFromSpecificContext<T>(T specificContext)

아마도 다음과 같이 작성하고 싶을 것입니다.

public interface ISrvThatCantBeGeneric
{
  int GetValueFromSpecificContext<T>(T specificContext) where T : SpecificContext;
}

public class SrvThatCantBeGeneric : ISrvThatCantBeGeneric
{
  public int GetValueFromSpecificContext<T>(T specificContext) where T : SpecificContext
  {
    return specificContext.MyProperty;
  }
}

public class SpecificContext
{
  public int MyProperty { get; set; } = 42;
}

public class SpecificContextChild : SpecificContext
{
  public SpecificContextChild()
  {
    MyProperty = 10;
  }
}

테스트

var server = new SrvThatCantBeGeneric();
var context = new SpecificContextChild();
Console.WriteLine(server.GetValueFromSpecificContext(context));

산출

10

또한 인터페이스와 클래스를 메서드 자체가 아닌 제네릭으로 승격 할 수 있습니다.

관련이있는 경우 :

public interface ISrvThatCantBeGeneric<T> where T : SpecificContext
{
  int GetValueFromSpecificContext(T specificContext);
}

public class SrvThatCantBeGeneric<T> : ISrvThatCantBeGeneric<T> where T : SpecificContext
{
  public int GetValueFromSpecificContext(T specificContext)
  {
    return specificContext.MyProperty;
  }
}

public class SpecificContext
{
  public int MyProperty { get; set; } = 42;
}

public class SpecificContextChild : SpecificContext
{

  public SpecificContextChild()
  {
    MyProperty = 10;
  }
}

var server = new SrvThatCantBeGeneric<SpecificContextChild>();
var context = new SpecificContextChild();
Console.WriteLine(server.GetValueFromSpecificContext(context));

또한 선호하거나 필요한 경우 기본 클래스 대신 인터페이스를 사용할 수 있습니다.

public interface IContext
{
  int MyProperty { get; set; }
}

비 일반 클래스 버전 :

public interface ISrvThatCantBeGeneric
{
  int GetValueFromSpecificContext<T>(T specificContext) where T : IContext;
}

public class SrvThatCantBeGeneric : ISrvThatCantBeGeneric
{
  public int GetValueFromSpecificContext<T>(T specificContext) where T : IContext
  {
    return specificContext.MyProperty;
  }
}

public class SpecificContext : IContext
{
  public int MyProperty { get; set; } = 42;
}

일반 클래스 버전 :

public interface ISrvThatCantBeGeneric<T> where T : IContext
{
  int GetValueFromSpecificContext(T specificContext);
}

public class SrvThatCantBeGeneric<T> : ISrvThatCantBeGeneric<T> where T : IContext
{
  public int GetValueFromSpecificContext(T specificContext)
  {
    return specificContext.MyProperty;
  }
}

public class SpecificContext : IContext
{
  public int MyProperty { get; set; } = 42;
}

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

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

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

분류에서Dev

제네릭 유형의 속성에 액세스

분류에서Dev

C #에서 내부 제네릭의 멤버에 액세스

분류에서Dev

제네릭 유형의 제네릭 클래스에서 유형 인수에 액세스

분류에서Dev

제네릭 메서드에서 형식 인수로 사용중인 클래스의 기본 클래스 속성에 액세스 할 수 없습니다.

분류에서Dev

제네릭 함수에 전달할 때 @Published 속성의 래핑 된 값에 액세스하는 방법

분류에서Dev

C #에서 제네릭 함수 형식 인수 캐스팅

분류에서Dev

C # 제네릭 형식의 다형성

분류에서Dev

제네릭 형식 함수의 'something'형식에 속성이 없습니다.

분류에서Dev

제네릭 함수의 제네릭 형식의 HashSet에서 HashSet <T> 반환

분류에서Dev

확장 제네릭에서 속성 유형 액세스

분류에서Dev

별도의 함수 C # WinForms에서 생성 된 TabPage의 액세스 제어

분류에서Dev

C #으로 제네릭 클래스의 동적 클래스 속성에 액세스하는 방법은 무엇입니까?

분류에서Dev

C # 제네릭 형식의 컨텍스트에서 형식 ID는 무엇입니까?

분류에서Dev

컴파일러에서 찾을 수없는 제네릭 형식 클래스의 C # 확장 메서드

분류에서Dev

C #에서 모든 유형의 제네릭으로 캐스팅

분류에서Dev

함수의 형식적 인수에서 선택에 액세스

분류에서Dev

Objective C의 클래스 외부에서 속성에 액세스

분류에서Dev

제네릭 클래스에 중첩 된 클래스를 C #의 형식 매개 변수로 사용

분류에서Dev

추상 클래스 C #에서 중첩 된 제네릭 / 중첩 된 제네릭의 상속

분류에서Dev

C ++에서 Object Pointer의 속성에 액세스

분류에서Dev

식에 사용할 제네릭 유형의 속성 유형 가져 오기

분류에서Dev

제네릭 유형의 비 제네릭 속성에 대한 유효성 검사

분류에서Dev

AutoMoq에서 제네릭 클래스의 속성을 매개 변수로 전달

분류에서Dev

형식에 대한 제약 조건이있는 제네릭의 C # 이름

분류에서Dev

C ++ : 제네릭 클래스의 비 제네릭 메서드?

분류에서Dev

C ++ : 제네릭 클래스의 비 제네릭 메서드?

분류에서Dev

다른 버튼에서 버튼의 변수에 액세스 (C # 형식)

분류에서Dev

루프 내의 함수에서 객체 속성 액세스

분류에서Dev

C #에서 제네릭 클래스의 속성을 어떻게 반복합니까?

Related 관련 기사

  1. 1

    제네릭 유형의 속성에 액세스

  2. 2

    C #에서 내부 제네릭의 멤버에 액세스

  3. 3

    제네릭 유형의 제네릭 클래스에서 유형 인수에 액세스

  4. 4

    제네릭 메서드에서 형식 인수로 사용중인 클래스의 기본 클래스 속성에 액세스 할 수 없습니다.

  5. 5

    제네릭 함수에 전달할 때 @Published 속성의 래핑 된 값에 액세스하는 방법

  6. 6

    C #에서 제네릭 함수 형식 인수 캐스팅

  7. 7

    C # 제네릭 형식의 다형성

  8. 8

    제네릭 형식 함수의 'something'형식에 속성이 없습니다.

  9. 9

    제네릭 함수의 제네릭 형식의 HashSet에서 HashSet <T> 반환

  10. 10

    확장 제네릭에서 속성 유형 액세스

  11. 11

    별도의 함수 C # WinForms에서 생성 된 TabPage의 액세스 제어

  12. 12

    C #으로 제네릭 클래스의 동적 클래스 속성에 액세스하는 방법은 무엇입니까?

  13. 13

    C # 제네릭 형식의 컨텍스트에서 형식 ID는 무엇입니까?

  14. 14

    컴파일러에서 찾을 수없는 제네릭 형식 클래스의 C # 확장 메서드

  15. 15

    C #에서 모든 유형의 제네릭으로 캐스팅

  16. 16

    함수의 형식적 인수에서 선택에 액세스

  17. 17

    Objective C의 클래스 외부에서 속성에 액세스

  18. 18

    제네릭 클래스에 중첩 된 클래스를 C #의 형식 매개 변수로 사용

  19. 19

    추상 클래스 C #에서 중첩 된 제네릭 / 중첩 된 제네릭의 상속

  20. 20

    C ++에서 Object Pointer의 속성에 액세스

  21. 21

    식에 사용할 제네릭 유형의 속성 유형 가져 오기

  22. 22

    제네릭 유형의 비 제네릭 속성에 대한 유효성 검사

  23. 23

    AutoMoq에서 제네릭 클래스의 속성을 매개 변수로 전달

  24. 24

    형식에 대한 제약 조건이있는 제네릭의 C # 이름

  25. 25

    C ++ : 제네릭 클래스의 비 제네릭 메서드?

  26. 26

    C ++ : 제네릭 클래스의 비 제네릭 메서드?

  27. 27

    다른 버튼에서 버튼의 변수에 액세스 (C # 형식)

  28. 28

    루프 내의 함수에서 객체 속성 액세스

  29. 29

    C #에서 제네릭 클래스의 속성을 어떻게 반복합니까?

뜨겁다태그

보관