Home > Back-end >  Indirectly having interface property
Indirectly having interface property

Time:01-01

I have a interface like this:

interface IName
    {
        string Name { get; set; }
    }

and a Class like this:

public class ClassN
    {
        public int N { get; set; }
    }

N in that Class is a int, and the interface requires a string Name. I want the int N to be converted to string and be counted as Name in the interface.

So that when i do T.name i get the .N.toString().

Is it possible?

Name = N.ToString();

Example:

N = 2; than Name = 2; (but as string)

P.S: Sry the question was confusing. Tried again.

CodePudding user response:

You can use an explicit interface implementation:

public class ClassN : IName
{
    string IName.Name
    {
         get { return N.ToString(); }
         set{ if(int.TryParse(value, out int i)) N = i; }
    }
    
    public int N { get; set; }
}

CodePudding user response:

You can use generic configuration.

interface IName<T>
{
    T Name { get; set; }
}

If you want a casting related configuration, you can use object.

interface IName
{
    object Name { get; set; }
}
  •  Tags:  
  • c#
  • Related