C #: implementing an interface with a property of any type

I am trying to implement an interface that requires one property, but I do not pay much attention to its type. For instance:

public interface IName
{
    dynamic Name {get; set;}
}

Then, if I have a class, I would like to implement an IName interface with a string type:

public class Person : IName
{
     public string Name {get; set;}
} 

This leads to an error. I know that I can make the interface IName adopt a common argument IName<T>, but it makes me create a bunch of overloaded functions that accept IName<string>, IName<NameObj>, IName<etc>instead of casting within a single function.

How can I require a class to contain a property?

+3
source share
4 answers

I cannot verify this now, but perhaps you can implement the interface explicitly.

public class Person : IName
{
    public string Name {get; set;}

    dynamic IName.Name {
        get { return this.Name; }
        set { this.Name = value as string; }
    }
} 
+5
source
interface IName<T>
{
    T Name { get; set; }
}

class Person : IName<string>
{
    public string Name { get; set; }
}
+9

, . .

    public interface IName
    {
        dynamic name { get; set; }
    }

    public class Person: IName
    {
        private string _name;
        public dynamic name { get { return _name; } set { _name = value;} }
    }

:

note that you need to be careful about what you pass for the name, since the type of the value will only be checked at runtime (the joy of using dynamic types).

Person p = new Person();
p.name = "me"; // compiles and runs fine, "me" is a string
p.name = p; // compiles fine, but will run into problems at runtime because p is not a string
+1
source

Do

public string Name {get; set;}

and create an object of type return value.

0
source

Source: https://habr.com/ru/post/1785695/


All Articles