如何在c#

时间:2019-02-03 04:12:35

标签: c# heterogeneous-array

我有3个不同的类(1个父类和2个子类),并且创建了一个异构数组:

Parent[] parentArray =  new Parent[9];

我想按此顺序用3个父对象,3个child1对象和3个child2对象填充此数组。

我想知道是否有比这更优雅的方法:

parentArray[0] = new Parent();

parentArray[1] = new Parent();

parentArray[2] = new Parent();

parentArray[3] = new Child1();

parentArray[4] = new Child1();

....

parentArray[9] = new Child2();

谢谢!

3 个答案:

答案 0 :(得分:1)

喜欢吗?

cmd

答案 1 :(得分:1)

我个人认为您应该使用对象初始化程序。但是,由于无聊,您可以使用Linq和通用工厂方法。

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled=true)
@ComponentScan("com.project")
public class AppSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService authService;

    @Autowired
    PersistentTokenRepository tokenRepository;

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(authService);
        auth.authenticationProvider(authenticationProvider());
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
      return new BCryptPasswordEncoder();
    }

    @Bean
    public DaoAuthenticationProvider authenticationProvider() {
        DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
        authenticationProvider.setUserDetailsService(authService);
        authenticationProvider.setPasswordEncoder(passwordEncoder());
        return authenticationProvider;
    }

    @Bean
    public PersistentTokenBasedRememberMeServices getPersistentTokenBasedRememberMeServices() {
        return new PersistentTokenBasedRememberMeServices("remember-me", authService, tokenRepository);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
         http.authorizeRequests().anyRequest().authenticated()
         .and()
        .formLogin()
        .loginProcessingUrl("/login")
        .defaultSuccessUrl("/login")
        .and()
        .logout().logoutUrl("/logout")
        .logoutSuccessUrl("/")
        .and().csrf()
        .and().rememberMe().rememberMeParameter("remember-me").tokenRepository(tokenRepository).tokenValiditySeconds(86400);
    }
}

答案 2 :(得分:0)

在这种情况下,您想重复执行一定数量的操作。循环通常用于执行此操作。因为您正在初始化数组,所以for循环非常适合,因为它们公开了可用于索引数组的整数。在您的方案中,您可以使用三个这样的循环。

Parent[] parentArray = new Parent[9];

for (int i = 0; i < 3; i++)
{
    parentArray[i] = new Parent();
}

for (int i = 3; i < 6; i++)
{
    parentArray[i] = new Child1();
}

for (int i = 6; i < 9; i++)
{
    parentArray[i] = new Child2();
}