質問

私は、タイプをとる一般的な静的クラスを備えたC#Webサービスで働いています。なぜこれがコンパイルされないのか疑問に思っていました:

Type type1 = typeof(MySnazzyType);
Assert.AreEqual(0, ConnectionPool_Accessor<type1>._pool.Count);

このエラーが発生します。

タイプまたは名前空間名「Type1」は見つかりませんでした(使用法またはアセンブリリファレンスを欠いていますか?)

そして、私が浮かんだとき、resharper type1 その2行目のコードで、「タイプまたは名前空間名が期待される」と言います。良い、 type1 タイプ!タイプの変数です Type!私がそうするならば、それはうまくいきません:

Type type1 = typeof(MySnazzyType);
Assert.AreEqual(0, ConnectionPool_Accessor<typeof(type1)>._pool.Count);

私は自分のタイプをいくつかの異なるものに割り当てたいと思っていました Type 変数を使用して、タイプアウトする代わりに、異なる一般的な静的クラスをテストする際に使用するだけです MySnazzyType 毎回。どんなアイデア、または私はやっていることに固執していますか:

Assert.AreEqual(0, ConnectionPool_Accessor<MySnazzyType>._pool.Count);

編集: 明確にするために、 MySnazzyTypeいいえ 一般的なクラスではなく、一般的なクラスからも継承していません。ここで唯一の一般的なクラスはです ConnectionPool_Accessor.

Pavelのコメントのおかげで、「本質的に、あなたの問題はC#が静的にタイプされた言語であるということです」、Rubyが私を台無しにしたことを知っています。 ;)

役に立ちましたか?

解決

First of all, ReSharper is actually correct. It isn't a type, it's a variable. Granted, it's a variable that is holding the reflection object that corresponds to a type, but that isn't enough.

Between the <...> brackets, you have to write the name of a type, not the name of any other identifier.

You can construct generic objects through reflection, however, and access their properties, even static ones, so you should be able to rewrite the code to do that, however, have you looked at NUnit 2.5?

From the latest release notes, it appears that unit test classes can now be generic, and you can specify with an attribute on the test class which types to test it with.

This would allow you to write something like this (note, I have not tested this, I only looked up the names of the new attributes in the documentation):

[TestFixture(typeof(MySnazzyType))]
[TestFixture(typeof(MyOtherSnazzyType))]
public class Tests<T>
{
    [Test]
    public void PoolCount_IsZero()
    {
        Assert.AreEqual(0, ConnectionPool_Accessor<T>._pool.Count);
    }
}

他のヒント

Generic types are evaluated at compile time, not in runtime. Since it cannot be determined at runtime time what type1 will be, this construct is not allowed.

This is actually what Resharper says: type1 is not a Type, it's a variable of the type Type, (just as it could be an object of the type String).

The TestFixture attribute should set you up, but just for the heck of it: if you wanted to do all this at runtime, you could do so using reflection.

Type poolType = typeof(ConnectionPool_Accessor<>);
Type snazzyType = typeof(MySnazzyType); // Or however you want to get the appropriate Type
poolType.MakeGenericType(snazzyType);

You could then proceed to do whatever you want using reflection on poolType. Of course, that will be a major pain in the butt unless you use C# 4.0 dynamic typing.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top