C#: Implement an Interface witha Property of Any Type
I'm trying to implement an interface that requires a single property, but I don't explicitly care what type it is. For example:
public interface IName
{
dynamic Name {get; set;}
}
Then if I have a class I'd like to implement the IName interface with a type of string:
public class Person : IName
{
public string Name {get; set;}
}
This however raises an error. I know I could make the interface IName take a generic arguement IName<T>
but that forces me to create a bunch of overloaded functions that take IName<string>
, IName<NameObj>
, IName<etc>
instead of casting withi开发者_StackOverflow社区n a single function.
How can I require that a class contains a property?
interface IName<T>
{
T Name { get; set; }
}
class Person : IName<string>
{
public string Name { get; set; }
}
I am unable to test this now, but maybe you could 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; }
}
}
Returning a dynamic allows you to return any type you please. Simply declare the type in your implementing class to be dynamic.
public interface IName
{
dynamic name { get; set; }
}
public class Person: IName
{
private string _name;
public dynamic name { get { return _name; } set { _name = value;} }
}
edit:
note that you'll have to be careful about what you pass to name since the type of value will only be checked at runtime (the joys 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
Make
public string Name {get; set;}
and make the return type Object.
精彩评论