C# - 在不知道变量会是什么的情况下初始化变量

发布于 2024-11-17 11:41:58 字数 1656 浏览 4 评论 0原文

我的数据库中有两个不同的表,每个表都根据用户的“排序顺序”显示给用户。我编写了两个函数,它们采用一行(或实体)并将其排序顺序与最接近的排序顺序交换(向上或向下,取决于正在执行的函数)。我需要使这些函数适用于两个不同的表,具体取决于事件发生的位置(具有相同功能的多个网格视图)。这是我到目前为止所拥有的(同样,有一个几乎相同的向下移动功能,但我不会发布它,因为它是多余的):

protected void moveUp(String ValId, String dbName)
    {
        int ValueId = Convert.ToInt32(ValId);
        DataModel.DataAccess.Entities dc = new DataModel.DataAccess.Entities();
        if (dbName.ToLower() == "table1")
        {
            DataModel.DataAccess.Table1 currentValue = dc.Table1.Single(table1item => table1item.Table1ItemId == ValueId);
        }
        else if (dbName.ToLower() == "table2")
        {
            DataModel.DataAccess.Table2 currentValue = dc.Table2.Single(table2item => table2item.Table2ItemId == ValueId);
        }
        try
        {
            //make the change and update the database and gridview
        }
        catch (InvalidOperationException)
        {
        }
    }

明显的问题是我需要启动currentValue 变量 if 语句之前,否则有“可能”它永远不会被声明,因此函数的其余部分(使用 currentValue 变量),行不通的。

我的问题是:如果我还不确定变量会是什么,我应该如何在 if 语句之前初始化变量?我认为这可能有效,但它说我仍然需要初始化它(“必须初始化隐式类型的局部变量”):

    var currentValue; //this is the line where I get the error message above
    if (dbName.ToLower() == "table1")
    {
        currentValue = (DataModel.DataAccess.Table1)dc.Table1.Single(table1item => table1item.Table1ItemId == ValueId);
    }
    else if (dbName.ToLower() == "table2")
    {
        currentValue = (DataModel.DataAccess.Table2)dc.Table2.Single(table2item => table2item.Table2ItemId == ValueId);
    }

[编辑]更改了标题以使其更准确地反映我的问题

I have two different tables in my database, and each are displayed to the user based on their "SortOrder". I have written two functions that take a row (or entity) and swaps its sort order with the one nearest it (up or down, depending on which function is being executed). I need to make these functions work for two different tables, depending on where the event is occurring (multiple gridviews with identical functionality). Here is what I have so far (again, there is an almost identical function for moving down, but I won't post that because it would be redundant):

protected void moveUp(String ValId, String dbName)
    {
        int ValueId = Convert.ToInt32(ValId);
        DataModel.DataAccess.Entities dc = new DataModel.DataAccess.Entities();
        if (dbName.ToLower() == "table1")
        {
            DataModel.DataAccess.Table1 currentValue = dc.Table1.Single(table1item => table1item.Table1ItemId == ValueId);
        }
        else if (dbName.ToLower() == "table2")
        {
            DataModel.DataAccess.Table2 currentValue = dc.Table2.Single(table2item => table2item.Table2ItemId == ValueId);
        }
        try
        {
            //make the change and update the database and gridview
        }
        catch (InvalidOperationException)
        {
        }
    }

The obvious problem is that I need to initiate the currentValue variable before the if statements, otherwise there is the "possibility" of it never being declared, and therefore the rest of the function (that utilizes the currentValue variable), won't work.

My question is this: How should I initialize the variable before the if statements, if I'm not sure what its going to be yet? I thought that this might work, but it says I still need to initialize it ("implicitly-typed local variables must be initialized"):

    var currentValue; //this is the line where I get the error message above
    if (dbName.ToLower() == "table1")
    {
        currentValue = (DataModel.DataAccess.Table1)dc.Table1.Single(table1item => table1item.Table1ItemId == ValueId);
    }
    else if (dbName.ToLower() == "table2")
    {
        currentValue = (DataModel.DataAccess.Table2)dc.Table2.Single(table2item => table2item.Table2ItemId == ValueId);
    }

[EDIT] Changed the title to make it more accurately reflect my question

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

庆幸我还是我 2024-11-24 11:41:58

在 C# 中,所有类型都需要一个类型。如果您的 Table# 类型扩展 DataModel.DataAccess.Table,请使用此:

DataModel.DataAccess.Table currentValue;

否则,您需要找到一个公共基类(对象是它们的曾祖父)全部)。

object currentValue;

由于您没有初始化 currentValue,编译器无法知道 var 所指的类型。这就是为什么你会得到例外。

附录:也许,您可以使用通用方法,而不是传入表的名称,如下所示:

moveUp(dc.Table1, item => item.Table1Key, "george");

void moveUp<T> (IEnumerable<T> table, Func<T,string> keySelector, string ValId)
{
    T currentValue = table.Single(item => keySelector(item) == ValueId);

    try
    {
        //make the change and update the database and gridview
    }
    catch (InvalidOperationException)
    {
    }
}

In C#, all types need a type. If your Table# types extend DataModel.DataAccess.Table, use this:

DataModel.DataAccess.Table currentValue;

Otherwise, you'll need to find a common base class (object being the great-granddaddy of them all).

object currentValue;

Since you didn't initialize currentValue, the compiler can't know what type you mean by var. That's why you are getting the exception.

Addendum: Perhaps, instead of passing in the name of the table, you can use a generic method, like this:

moveUp(dc.Table1, item => item.Table1Key, "george");

void moveUp<T> (IEnumerable<T> table, Func<T,string> keySelector, string ValId)
{
    T currentValue = table.Single(item => keySelector(item) == ValueId);

    try
    {
        //make the change and update the database and gridview
    }
    catch (InvalidOperationException)
    {
    }
}
無處可尋 2024-11-24 11:41:58

使用类型对象代替 var,尽管我可能会重写整个过程并使用一致(和标准)的命名约定。

所以:

object currentValue = null;

Instead of var, use type object although I would probably rewrite this whole proc and use consistent (and standard) naming conventions.

so:

object currentValue = null;
待天淡蓝洁白时 2024-11-24 11:41:58

您可以尝试编写每个实体使用的接口以及接受该接口的函数。

public interface ISortableEntity
{
    int ID { get; set; }
    int SortOrder { get; set; }
}


 public class DataFunctions
{
    public static void MoveUp(string dbName, int valID)
    {
        var db = //Get your context here;
        List<KeyValuePair<string, object>> keys = new List<KeyValuePair<string, object>>();
        keys.Add(new KeyValuePair<string, object>("ID", valID));

        ISortableEntity entity = db.GetObjectByKey(new System.Data.EntityKey(dbName, keys)) as ISortableEntity;

        if (entity != null)
        {
            entity.SortOrder += 1;
        }

        db.SaveChanges();
    }
}

You can try writing an interface which each entity uses and a function that accepts that interface.

public interface ISortableEntity
{
    int ID { get; set; }
    int SortOrder { get; set; }
}


 public class DataFunctions
{
    public static void MoveUp(string dbName, int valID)
    {
        var db = //Get your context here;
        List<KeyValuePair<string, object>> keys = new List<KeyValuePair<string, object>>();
        keys.Add(new KeyValuePair<string, object>("ID", valID));

        ISortableEntity entity = db.GetObjectByKey(new System.Data.EntityKey(dbName, keys)) as ISortableEntity;

        if (entity != null)
        {
            entity.SortOrder += 1;
        }

        db.SaveChanges();
    }
}
美男兮 2024-11-24 11:41:58

您是否不知道变量的类型,这就是您隐式声明它的原因(“var”,而不是“int”)?

您不必初始化显式类型 - 隐式类型需要它,因为它们通过给定的值确定其类型。

Do you not know the type of the variable, which is why you're declaring it implicitly ('var', as opposed to, say, 'int')?

You don't have to initialize explicit types - implicit types require it because they figure out their type by the value given.

噩梦成真你也成魔 2024-11-24 11:41:58

解决方案是接口。您的 Table 1 和 Table 2 类应该实现一个带有 CurrentValue 属性的接口(例如 ISortableTable 或任何您想要调用的名称)。 Table1 的 CurrentValue 属性实现将为 Table1 返回正确的结果,而 Table2 的 CurrentValue 属性将为 Table2 返回正确的结果。然后,您的排序函数可以与实现 ISortableInterface 的任何类一起使用,并与相应对象的 CurrentValue 属性一起使用。

The solution is interfaces. Your Table 1 and Table 2 classes should implement an interface (such as ISortableTable or whatever you want to call it) with a property for CurrentValue. Table1's CurrentValue property implementation would return the correct result for Table1 and Table2's CurrentValue property would return the correct result for Table2. Then your sorting function can work with any class that implements the ISortableInterface and work with the respective object's CurrentValue property.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文