小编use*_*188的帖子

无法将基类型的变量作为输出参数传递?

刚刚注意到这不起作用:

var dict = new Dictionary<int, XElement>();
XContainer element;
//...
if (dict.TryGetValue(idx, out element)) { //...
Run Code Online (Sandbox Code Playgroud)

然后我尝试了这个:

class A { }
class B : A { }

class Program {
    static void Main() {
        A a;
        a = Ret();  // no error, ok
        Ref(ref a); // compiler error, ok...
        Out(out a); // compiler error, lolwut?!
    }
    static B Ret() { return null; }
    static void Ref(ref B b) { }
    static void Out(out B b) { b = null; } …
Run Code Online (Sandbox Code Playgroud)

c# out

5
推荐指数
1
解决办法
589
查看次数

确定type是否是泛型类型的子类

class Program
{
    static void Main(string[] args) {
        Check(new Foo());
        Check(new Bar());
    }
    static void Check<T>(T obj) {
        // "The type T cannot be used as type parameter..."
        if (typeof(T).IsSubclassOf(typeof(Entity<T>))) {
            System.Console.WriteLine("obj is Entity<T>");
        }
    }
}
class Entity<T> where T : Entity<T>{ }
class Foo : Entity<Foo> { }
class Bar { }
Run Code Online (Sandbox Code Playgroud)

使这个东西编译的正确方法是什么?我可以Entity<T>从非泛型EntityBase类中typeof(Entity<>).MakeGenericType(typeof(T))继承子类,或者可以尝试查看它是否成功,但有没有一种方法可以不滥用try { } catch { }块或类型层次结构?

有一些方法Type就像它们可能有用一样GetGenericArguments,GetGenericParameterConstraints但是我对于如何使用它们完全无能为力......

c# generics reflection

5
推荐指数
1
解决办法
1818
查看次数

标签 统计

c# ×2

generics ×1

out ×1

reflection ×1