C#use方法用于多个类/类型

时间:2017-07-13 16:44:34

标签: c# sqlite

我喜欢将方法用于不同类型的类/类型。我可以这样做:

public void ClearTable(string type)
    {
        try
        {
            using (var connection = new SQLiteConnection(platform, dbPath))
            {
                switch (type)
                {
                    case "Project":
                        connection.DropTable<Project>();
                        connection.CreateTable<Project>();
                        break;

                    case "Task":
                        connection.DropTable<Task>();
                        connection.CreateTable<Task>();
                        break;

                    default:
                        break;
                }

            }
        }
        catch (SQLiteException ex)
        {
            Log.Info("SQLiteEx", ex.Message);
        }

    }

例如&#34; Project&#34;在DropTable中是一个类的名称。但我更喜欢更通用的东西(这是我不知道该怎么做的部分):

public void ClearTable(Type t)
    {
        try
        {
            using (var connection = new SQLiteConnection(platform, dbPath))
            {
                connection.DropTable<t>();
                connection.CreateTable<t>();
            }
        }
        catch (SQLiteException ex)
        {
            Log.Info("SQLiteEx", ex.Message);
        }

    }

如何使用类似上一种方法的东西来支持多种类/类型?

2 个答案:

答案 0 :(得分:4)

您正在寻找泛型

使用泛型,您可以编写如下代码:

public void ClearTable<TType>()
{
    try
    {
        using (var connection = new SQLiteConnection(platform, dbPath))
        {
            connection.DropTable<TType>();
            connection.CreateTable<TType>();
        }
    }
    catch (SQLiteException ex)
    {
        Log.Info("SQLiteEx", ex.Message);
    }
}

然后,您可以调用该方法并将任何类型作为通用参数:

ClearTable<MyDomainModel>();

另外,您可以使用TType子句限制泛型参数where

public void ClearTable<TType>()
    where TType : IDomainModel
{
    // your code goes here
}

现在,您只能将从IDomainModel继承的类型作为通用参数。

答案 1 :(得分:1)

取决于调用ClearTable的代码是什么样的。

编译时间绑定

如果它在编译时知道类型,您可以将原型更改为

public void ClearTable<T>() 

...并用

调用它
var myClass = new MyClass();
myClass.ClearTable<Task>();   

myClass.ClearTable<Project>(); 

运行时绑定

如果直到运行时才知道该类型,并且您确实必须将其作为字符串传递,那么您可以设置如下的委托字典:

class MyClass
{
    private readonly Dictionary<string, Action<SQLLiteConnection>> _actions = new Dictionary<string, Action<SQLLiteConnection>>();

    public MyClass()
    {
        _actions.Add("Project", conn => conn.DropTable<Project>());
        _actions.Add("Task", conn => conn.DropTable<Task>());
    }

    public void ClearTable(string type)
    {
        try
        {
            using (var connection = new SQLiteConnection(platform, dbPath))
            {
                var action = _actions[type](connection);
                action(connection);
            }
        }
        catch (KeyNotFoundException ex1)
        { 
            Log.Info(String.Format("{0} is not a supported type.", type));
        }
        catch (SQLiteException ex2)
        {
            Log.Info("SQLiteEx", ex2.Message);
        }
    }
}