相关疑难解决方法(0)

为什么我的C#泛型方法中出现"错误:...必须是引用类型"?

在各种数据库表中,我有一个属性和一个值列.我正在使用Linq to SQL来访问数据库.

我正在编写一个方法,它返回一个包含从给定数据库表中检索的属性/值的字典:

private static Dictionary<string, string> GetProperties<T>(Table<T> table)
{
    Dictionary<string, string> properties = new Dictionary<string, string>();

    foreach (var row in table)
    {
        properties[row.Property]=row.Value;
    }

    return properties;
}
Run Code Online (Sandbox Code Playgroud)

编译后,我得到:

Error 1 The type 'T' must be a reference type in order to use it as parameter 'TEntity' in the generic type or method 'System.Data.Linq.Table<TEntity>'

我试过没有运气的搜索这个错误信息.

搜索StackOverflow时,这个问题似乎相似,但是关于参数List:Generic List <T>作为方法的参数 - 尽管参数仍然不是该问题的答案中的引用类型.

阅读MSDN上的C#编程指南:http://msdn.microsoft.com/en-us/library/twcad0zb(VS.80).aspx我看到他们的例子都通过引用传递参数.但是,在我的特定情况下,我无法看到如何通过引用传递,因为泛型类型仅用于指定Table的泛型类型.

任何指针都将非常感激.

PS:如果我需要时间接受答案,可能会出现这种情况,因为目前无法访问此功能(我是盲人并使用屏幕阅读器).

c# linq-to-sql

28
推荐指数
2
解决办法
2万
查看次数

C#不可分配类型 - 泛型

所以我只是在使用我正在处理的状态机类型,并且大多想要尝试使用Activator.CreateInstance方法来查看它是什么样的,我遇到了一个问题,我似乎无法使用该where子句作为我想.如果我只是个白痴,我会提前道歉,大家都会把我从这里拉出来.所以我有2个小班.

public class TransitionContainer<TTransition, TStateTo> :
    ITransitionContainer<TTransition, TStateTo>
    where TTransition : ITransition
    where TStateTo : IState
{
    public TransitionContainer()
    {
        StateTo = typeof(TStateTo);
        Transition = Activator.CreateInstance<TTransition>();
    }

    public Type StateTo { get; private set; }

    public TTransition Transition { get; private set; }
}
Run Code Online (Sandbox Code Playgroud)

以及

  public class StateContainer<T> : IStateContainer<T> where T : IState
{
    private Dictionary<Type, TransitionContainer<ITransition, IState>> _transitions =
        new Dictionary<Type, TransitionContainer<ITransition, IState>>();

    public StateContainer()
    {
        State = Activator.CreateInstance<T>();
    }

    public T State { get; private …
Run Code Online (Sandbox Code Playgroud)

c# generics polymorphism

6
推荐指数
1
解决办法
588
查看次数

标签 统计

c# ×2

generics ×1

linq-to-sql ×1

polymorphism ×1