简体   繁体   中英

Initialize and scope a generic abstract class

I have the following code

            var dataCollection;
            if (ViewBag.WageType.ToLower() == "perm")
            {
                dataCollection = ViewBag.PermWageIndex;
            }
            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?

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.

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 technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM