どのようインスタンスを生成するオブジェクトの専用コンストラクタクライアントまで、フルのC#?
-
22-08-2019 - |
質問
ただ見てかえって反射あります。すことができませんでしたがなければいけなかったと SqlParameterCollection
なcreatableユーザーがいない間違いで).残念ながら見つからない場合などではない。
誰でもできるので共有してくださいこう。ないかと考えで有効なアプローチの開発、私は非常に興味がある可能性を行っています。
解決
// the types of the constructor parameters, in order
// use an empty Type[] array if the constructor takes no parameters
Type[] paramTypes = new Type[] { typeof(string), typeof(int) };
// the values of the constructor parameters, in order
// use an empty object[] array if the constructor takes no parameters
object[] paramValues = new object[] { "test", 42 };
TheTypeYouWantToInstantiate instance =
Construct<TheTypeYouWantToInstantiate>(paramTypes, paramValues);
// ...
public static T Construct<T>(Type[] paramTypes, object[] paramValues)
{
Type t = typeof(T);
ConstructorInfo ci = t.GetConstructor(
BindingFlags.Instance | BindingFlags.NonPublic,
null, paramTypes, null);
return (T)ci.Invoke(paramValues);
}
他のヒント
できるものではなく、一切の過負荷の 活性化剤です。CreateInstance このためには: Activator.CreateInstance(Type type, bool nonPublic)
使用 true
のための nonPublic
引数です。ので true
試合を公開又は非公開のデフォルトのコンストラクタ;や false
試合だけ公共のデフォルトのコンストラクタです。
例えば:
class Program
{
public static void Main(string[] args)
{
Type type=typeof(Foo);
Foo f=(Foo)Activator.CreateInstance(type,true);
}
}
class Foo
{
private Foo()
{
}
}
これはあなたが後にした質問ですか? Activator.CreateInstanceプライベート密封されたクラスを持つ
、それはそれはあなたのアプローチは、APIの作家が意図したものではない可能だということを意味し、聞こえます。ドキュメントを見て、このクラスを使用する推奨アプローチがありますかどうかを確認します。
は、をした場合のクラスを管理しているし、このパターンを実装したくない、それは一般的にクラスの静的メソッドを介して実装されています。これは、あまりにも、シングルトンパターンを構成する重要な概念である。
例
public PrivateCtorClass
{
private PrivateCtorClass()
{
}
public static PrivateCtorClass Create()
{
return new PrivateCtorClass();
}
}
public SomeOtherClass
{
public void SomeMethod()
{
var privateCtorClass = PrivateCtorClass.Create();
}
}
SqlCommandParameterのものが良い例です。彼らは、あなたがこのようなものを呼び出すことにより、パラメータを作成することを期待ます:
var command = IDbConnnection.CreateCommand(...);
command.Parameters.Add(command.CreateParameter(...));
それは、コマンドパラメータのプロパティまたはパラメータ/コマンドの再利用を設定することを証明しませんが、あなたのアイデアを得るために私の例では、偉大なコードではありません。
あなたのType
がprivate
かinternal
である場合にも役立ちます。
public static object CreatePrivateClassInstance(string typeName, object[] parameters)
{
Type type = AppDomain.CurrentDomain.GetAssemblies().
SelectMany(assembly => assembly.GetTypes()).FirstOrDefault(t => t.Name == typeName);
return type.GetConstructors()[0].Invoke(parameters);
}