上溯造型在使用.NET泛型造型、NET、泛型

由网友(≮小酒窩‰)分享简介:所以,我有一类这样的:So I've got a class like this:public class A { internal A(int i) { ... }public int Foo { get; set; }}本类,然后由一群生成的类继承,如:This class is then inherite...

所以,我有一类这样的:

So I've got a class like this:

public class A { 
  internal A(int i) { ... }
  public int Foo { get; set; }
}

本类,然后由一群生成的类继承,如:

This class is then inherited by a bunch of generated classes, eg:

public class B : A {
  ...
}

INT 基于构造函数不暴露在继承类(设计原因,我不想要它暴露)。在我的图书馆持有类定义的 A 我有一个方法是这样的:

The int based constructor isn't exposed to the inherited class (for design reasons I don't want it exposed). In my library which holds the definition for class A I've got a method like this:

public T Load<T>() where T : A {
  //do some stuff, create an instance of T from an int, then return it
}

然后我会使用这样的:

And then I'd use it like this:

B b = Helper.Load<B>();

因为我想用不暴露类的构造函数 B 当我这样做的typeof(T).GetConstructor(typeof运算(INT) )我不明白的构造回来,所以我想在想,我应该这样做:

Since the constructor I want to use isn't exposed to class B when I do typeof(T).GetConstructor(typeof(int)) I don't get the constructor back, so I want thinking that I'd do this:

return (T)new A(/*some int */);

但是,这给了我一个运行时错误 System.InvalidCastException ,我不能投了A型B型。

But that gives me a runtime error System.InvalidCastException, that I can't cast a type A to type B.

我如何去实现这个上溯造型?

How do I go about achieving this upcasting?

推荐答案

您可以只使用默认的构造函数,因此您可以实例化类型T的对象与新的()的约束。然后A类可以有一个虚拟(或抽象的根据自己的喜好)方法接受一个int作为参数并初始化构造函数运行之后的对象。

You can just use default constructors so you can instantiate objects of type T with the new() constraint. Then class A can have a virtual (or abstract to your liking) method that takes an int as an argument and initializes the object after the constructor has run.

public class A {
	internal A() { }
	internal Initialize(int i) { Foo = i; }
	public int Foo { get; set; }
}

public class B : A { 
	internal B() { }
}

...

public T Load<T>() where T : A, new() {
	var ret = new T();
	ret.Initialize(i);
	return ret;
}

如果你打算某种工厂模式,你并不需要犹豫初始化对象的部分构造函数调用外,只要你返回对象给调用者的控制权之前就已经完成。

If you intend some sort of factory pattern, you don't need to hesitate initializing parts of an object outside the constructor call as long as it is done before you return the object to the caller's control.

阅读全文

相关推荐

最新文章