简体   繁体   中英

C# enable to associate a value to an attribute of an interface

Hi I'm new in development and I'm trying to understand interfaces. Well I understood when to use them but I'm trying to associate a value to an attribute of an interface and I see an error.

public class Consumer : IUser
{
   public string Role { get; set; }
   public string Consumer { get; set }
}

..

public class Admin : IUser
{
   public string Role { get; set; }
   public string Admin { get; set; }
}

..

public interface IUser
{
    string Role { get; set; }
}

here the code i'm trying to test but I see "Use of unassigned local variable".

IUser user;
string role = "role test";

user.Role = role;

That's fine but I can't create a new instance of IUser because it's an interface. The only solution I found is to create a new Consumer and a new Admin but isn't what I'm trying to do. My plan is to retrieve the Role attribute from an XML, associate it with the Role of the IUser interface and return it. It'll be a responsibility of another part to check if the role is of an User or Admin

string xmlRole = reader.GetAttribute("Role");
var user = new IUser(); //error
//var user = new Customer(); works but not my plan
//var user = new Admin(); works but not my plan

user.Role = xmlRole;

First of all, interface is an contract, which means it only tells what methods class (which implements that interface) should have. While coding you can say, for example that given parameter should be of type IUser (Which basically means, that you can assign to it any class as long as it implements IUser).

Example:

interface IUser 
{
 bool Register();
}

class Administrator : IUser {}
class User : IUser {}

Then, you have method:

public bool HandlerRegister(IUser user)
{
//You can use method here, because you know that class used as parameter will 
//implement that method

  return user.Register();
}

In your case, when deserializing some XML you need to somehow say that given deserialized object is of type IUser.

But if I were you, I would just create class which represents Role and then, add that class as contract inside interface:)

Then, it would be preaty easy to assign it to all classes that implements yours interface.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM