变量是一种类型,在给定的上下文中无效

vas*_*123 0 c# asp.net-mvc

我有一个名为的界面 IUser

我有两个模型,User并且Guest它们都实现了IUser

我有一个类,称为CardOut有两个属性,CardUser

这是CardOut类的构造函数:

public CardOut(Interfaces.IUser User, Card Card) {
    this.User = User;
    this.Card = Card;
}
Run Code Online (Sandbox Code Playgroud)

我从数据库中获取了一些行,并根据单元格的类型,我创建了一个User或一个Guest.

foreach (IDictionary<string, string> row in rows) {
    if (row["type"] == "xxx") {
        User UserValue = new User();
        UserValue.buildById(int.Parse(row["user_id"]));
    } else {
        Guest UserValue = new Guest();
        UserValue.buildById(int.Parse(row["id"]));
    }
    Card Card = new Card();
    Card.buildCardByIndex(int.Parse(row["cardindex"]));
    CardOut CardOut = new CardOut(UserValue, Card);  //Here is the error
}
Run Code Online (Sandbox Code Playgroud)

当我想实例化一个新CardOut对象时,我收到此错误:

错误CS0103当前上下文中不存在名称"UserValue"

我该如何解决?我不能在if条件之外创建它,因为我不知道,我应该实例化哪个类.

Adr*_*ian 5

IUserif块外部声明一个类型的变量,并if在具体类型中实例化它.

编辑:添加一个演员,因为IUser似乎没有成员buildById.

foreach (IDictionary<string, string> row in rows) {
    IUser UserValue;
    if (row["type"] == "xxx") {
        UserValue = new User();
        ((User)UserValue).buildById(int.Parse(row["user_id"]));
    } else {
        UserValue = new Guest();
        ((Guest)UserValue).buildById(int.Parse(row["id"]));
    }
    Card Card = new Card();
    Card.buildCardByIndex(int.Parse(row["cardindex"]));
    CardOut CardOut = new CardOut(UserValue, Card);  
}
Run Code Online (Sandbox Code Playgroud)