Force Field Attribute C#

Asked

Viewed 81 times

1

Guys I have an Attribute class being her:

 class TipoServicoAttrib : System.Attribute
{
    public TipoOperacaoEnum TipoOperacao;
    public int CodigoOperacao;
}

I need that when I use, it is mandatory to fill in the Typooperacaoenum and Code. There is a way for this?

1 answer

2


Mandatory by nature does not, but when assigning or declaring this class, you can make it mandatory to use parameters in the constructor:

class TipoServicoAttrib : System.Attribute
{
    public TipoOperacaoEnum TipoOperacao;
    public int CodigoOperacao;

    public TipoServicoAttrib(TipoOperacaoEnum tipoOperacao, int codigoOperacao)
    {
        this.CodigoOperacao = codigoOperacao;
        this.TipoOperacao   = tipoOperacao;
    }

    private TipoServicoAttrib() {} // torna inacessível o construtor vazio
}

So every time TipoServicoAttrib call, these two values should be informed in the construction:

// OK
[TipoServicoAttrib(TipoOperacaoEnum.AlgumaCoisa, 200)]
public void OperacaoFoo() {}

// Erro
[TipoServicoAttrib]
public void OperacaoBar() {}

// Erro
[TipoServicoAttrib(TipoOperacaoEnum.AlgumaCoisa)]
public void OperacaoHello() {}

Since you are using two non-avoidable types, no null check is required at the beginning of the constructor. But if you are going to use a type that is Nullable, consider using this code in the first line of the constructor:

if(argumento is null) throw new ArgumentNullException(nameof(argumento));

So, if the value is null (and not empty), it will cause an error.

  • I tried to do so, but keeps giving error and does not allow to compile the code

  • What mistake it makes?

  • I’m adding the image to see how it is

  • @Himorrivel you added the methods outside the class. Do the following, delete everything inside the namespace (minus herself) and place this code (the first of my publication) within it ({...}).

  • 1

    what my fault, was exactly what I needed, obg

Browser other questions tagged

You are not signed in. Login or sign up in order to post.