Initialize and scope a generic abstract class
I have the following code
var dataCollection;
if (ViewBag.WageType.ToLower() == "perm")
{
dataCollection = ViewBag.PermWageIndex;
}
开发者_如何学Go else if(ViewBag.WageType.ToLower() == "trial")
{
dataCollection = ViewBag.TrialWageIndex;
}
The return type can be AbstractClass<Concrete1>
or AbstractClass<Concrete2>
. I must initialize the var at declaration. But, this means I lose the scope I desire. How can I modify this code to allow dynamic dataCollections without depending on the ViewBag?
You might be able to make AbstractClass<>
implement the interface IAbstractClass
and then make that the common type.
Whether this will work or not depends exactly which members the return type needs to access. Obviously, it won't be able to refer to any of the generically typed members, but that wouldn't make much sense anyway, since I'm assuming the consumer shouldn't know what the generic parameter is anyway.
The only way solving this is by providing a base class or interface which is inherited/implemented by Concrete1
and Concrete2
so you can declare dataCollection
as AbstractClass<ISomething>
.
Var is not dynamic typing it is resolved at compile time. Therefore you can not declare a variable without assignment (var x;
) because the compiler can not infer the type.
You can fall back to object
or dynamic
however you loose any type safety if you do so.
精彩评论