Приведение объекта к типу без обобщения - PullRequest
0 голосов
/ 09 ноября 2019
public class ErrorCode
{
    public int HttpStatus { get; private set; }
    public string JsonErrorCode { get; private set; }
    public Type ExceptionT { get; private set; }

    public ErrorCode(string pJsonErrorCode, int pHttpStatus, Type pExceptionType)
    {
        this.HttpStatus = pHttpStatus;
        this.JsonErrorCode = pJsonErrorCode;
    }

    public void ThrowException(string pMsg)
    {
        throw Activator.CreateInstance(ExceptionT, pMsg);
    }
}

Итак, как вы можете видеть, я пытаюсь создать экземпляр данного типа. Я не могу использовать Generics. потому что у меня есть словарь, который создает пул кодов ошибок.

Protocol.ErrorCodes.Add
(
    ErrorCodeType.ElementClickIntercepted,
    new ErrorCode
    (
        "element click intercepted", 
        400, 
        typeof(ElementClickInterceptedException)
    )
);

Приведенный выше код не работает, так как создаваемый тип имеет тип объекта и не является производным от system.exception

Приведенный выше код не будет работать с обобщениями, так как словарь должен понимать, что строится. Я не уверен, что делать здесь. мой словарь имеет около 50 различных исключений. Мысли?

Ответы [ 2 ]

2 голосов
/ 09 ноября 2019

Вам необходимо преобразовать созданный экземпляр в Exception

public class ErrorCode
{
  public int HttpStatus { get; private set; }
  public string JsonErrorCode { get; private set; }
  public Type ExceptionT { get; private set; }

  public ErrorCode(string pJsonErrorCode, int pHttpStatus, Type pExceptionType)
  {
    this.HttpStatus = pHttpStatus;
    this.JsonErrorCode = pJsonErrorCode;
    this.ExceptionT = pExceptionType;
  }

  public void ThrowException(string pMsg)
  {
    throw (Exception)Activator.CreateInstance(ExceptionT, pMsg);
  }
}

Вы можете заменить Exception на ElementClickInterceptedException или что-нибудь необходимое.

Тест

var error = new ErrorCode("test", 1, typeof(ArgumentException));
try
{
  error.ThrowException("error");
}
catch ( Exception ex )
{
  Console.WriteLine(ex.Message);
}

Фрагмент скрипта

Выход

error
1 голос
/ 09 ноября 2019

Я не могу использовать Generics. потому что у меня есть словарь, который создает пул кодов ошибок.

Да, вы действительно можете, и это правильное решение. Вам просто нужно объявить базовый интерфейс для вашего поискового словаря.

public interface IErrorCode
{
    int HttpStatus { get; }
    string JsonErrorCode { get; }
    void ThrowException(string pMsg);
}

public class ErrorCode<T> : IErrorCode where T : Exception
{
    public int HttpStatus { get; private set; }
    public string JsonErrorCode { get; private set; }

    public ErrorCode(string pJsonErrorCode, int pHttpStatus)
    {
        this.HttpStatus = pHttpStatus;
        this.JsonErrorCode = pJsonErrorCode;
    }

    public void ThrowException(string pMsg)
    {
        var exception = (T)Activator.CreateInstance
        (
            typeof(T), 
            new object[] { pMsg }
        );
        throw exception;
    }
}


//Declare the dictionary with the interface, not the concrete type
Protocol.ErrorCodes = new Dictionary<ErrorCodeType,IErrorCode>();

Protocol.ErrorCodes.Add
(
    ErrorCodeType.ElementClickIntercepted,
    new ErrorCode<ElementClickInterceptedException>
    (
        "element click intercepted", 
        400
    )
);

Если вам нужно работать с любым элементом в списке, вы можете использовать интерфейс - вам не нужно ничего приводить.

Чтобы получить статус HTTP:

var status = Protocol.ErrorCodes[key].HttpStatus;

Чтобы получить код ошибки Json:

var errorCode = Protocol.ErrorCodes[key].JsonErrorCode;

Обычно ваш код должен зависеть не от конкретных экземпляров, а от интерфейсов(согласно «D» в SOLID ).

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...